以编程方式将NSConstraints添加到故事板上的现有视图

时间:2016-03-05 23:31:50

标签: swift

我发现在编写故事板上的现有视图时以编程方式更正时,没有实现约束。这就是我所拥有的:

class ViewController: UIViewController {

    @IBOutlet weak var textField2: UITextField! {
        didSet {
            textField2.delegate = self
        }
    }

    func viewDidLoad() {
        super.viewDidLoad()

        let superview = self.view

        let textField1 = UITextField()
        textField1.backgroundColor = UIColor.greenColor()
        textField1.placeholder = "test text field"
        view.addSubview(textField1)
        textField1.translatesAutoresizingMaskIntoConstraints = false
        superview.addConstraint(NSLayoutConstraint(item: textField1, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: superview.frame.width * 0.50))
        superview.addConstraint(NSLayoutConstraint(item: textField1, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: superview.frame.height * 0.05))
        superview.addConstraint(NSLayoutConstraint(item: textField1, attribute: .CenterX, relatedBy: .Equal, toItem: superview, attribute: .CenterX, multiplier: 1, constant: 0))
        superview.addConstraint(NSLayoutConstraint(item: textField1, attribute: .CenterY, relatedBy: .Equal, toItem: superview, attribute: .CenterY, multiplier: 1, constant: 0))

        textField2.translatesAutoresizingMaskIntoConstraints = false
        superview.addConstraint(NSLayoutConstraint(item: textField2, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: superview.frame.width * 0.50))
        superview.addConstraint(NSLayoutConstraint(item: textField2, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: superview.frame.height * 0.05))
        superview.addConstraint(NSLayoutConstraint(item: textField2, attribute: .CenterX, relatedBy: .Equal, toItem: superview, attribute: .CenterX, multiplier: 1, constant: 0))
        superview.addConstraint(NSLayoutConstraint(item: textField2, attribute: .CenterY, relatedBy: .Equal, toItem: superview, attribute: .CenterY, multiplier: 1, constant: 0))

    }
}

textField1完美无缺。它被添加到视图的中心。然而,我拖动到故事板上的textField2偏离了中心。为什么会这样?

感谢

1 个答案:

答案 0 :(得分:1)

问题在于,如果视图来自故事板,例如textField2,那么已经有约束。说textField2.translatesAutoresizingMaskIntoConstraints = false并没有神奇地解决这个问题。您还需要以某种方式获取这些约束,并在代码中应用自己的约束之前删除它们。这可能很棘手,并且 这样做,这就是为什么你的观点行为不端。在这个阶段,你最好遵循这些简单的规则:

  • 如果视图来自故事板,则仅在故事板中设置其约束

  • 但是如果在代码中创建了一个视图,现在您可以说translatesAutoresizingMaskIntoConstraints = false并在代码中设置其约束