NSDictionaryOfVariableBindings swift equivalent?

前端 未结 7 1907
闹比i
闹比i 2020-12-08 01:47

The Apple documentation shows an unsettling blank space under the \'Creating a Dictionary\' section of the UIKit reference here.

Has anyone found a replacement for

7条回答
  •  轮回少年
    2020-12-08 02:12

    ObjC runtime to the rescue!

    i created an alternate solution, but it only works if each of the views are instance variables of the same object.

    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
    }
    

    can be used like this:

    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: "childA", "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))
    
        }
    
    }
    

    unfortunately you still have to type the variable name in as a string, but it will at least assert if there is a typo. this definitely won't work in all situations, but helpful nonetheless

提交回复
热议问题