Created
January 31, 2016 09:47
-
-
Save justAnotherDev/7d3f420c97ba87931cf0 to your computer and use it in GitHub Desktop.
DictionaryOfInstanceVariables - Swift version of NSDictionaryOfVariableBindings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func DictionaryOfInstanceVariables(container:AnyObject, objects: String ...) -> [String:AnyObject] { | |
var views = [String:AnyObject]() | |
for objectName in objects { | |
guard let object = object_getIvar(container, class_getInstanceVariable(container.dynamicType, objectName)) else { | |
assertionFailure("\(objectName) is not an ivar of: \(container)"); | |
continue | |
} | |
views[objectName] = object | |
} | |
return views | |
} | |
// Example Usage | |
import UIKit | |
class ViewController: UIViewController { | |
var childA: UIView = { | |
let view = UIView() | |
view.translatesAutoresizingMaskIntoConstraints = false | |
view.backgroundColor = UIColor.redColor() | |
return view | |
}() | |
var childB: UIButton = { | |
let view = UIButton() | |
view.setTitle("asdf", forState: .Normal) | |
view.translatesAutoresizingMaskIntoConstraints = false | |
view.backgroundColor = UIColor.blueColor() | |
return view | |
}() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
self.view.addSubview(childA) | |
self.view.addSubview(childB) | |
let views = DictionaryOfInstanceVariables(self, objects: "childC", "childB") | |
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[childA]|", options: [], metrics: nil, views: views)) | |
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[childB]|", options: [], metrics: nil, views: views)) | |
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[childA][childB(==childA)]|", options: [], metrics: nil, views: views)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
small note for swift 3.1
func DictionaryOfInstanceVariables(container:AnyObject, objects: String ...) -> [String:Any] {
var views = String:Any
for objectName in objects {
guard let object = object_getIvar(container, class_getInstanceVariable(type(of: container), objectName)) else {
assertionFailure("(objectName) is not an ivar of: (container)")
continue
}
views[objectName] = object
}
return views
}
AnyObject --> Any
container.dynamicType --> type(of: container)
Regards,
Sergey