我允许用户在按下按钮时创建一个新的文本字段。我想以编程方式从现有文本字段复制前导和尾随约束。我的代码:
@IBAction func addAnotherTextField(sender: AnyObject) {
let newTextField = UITextField.init(frame: CGRectMake(20, positionY, self.view.frame.size.width-40, 30))
newTextField.delegate = self
newTextField.tag = fieldCount
newTextField.placeholder = "You created this!"
newTextField.borderStyle = UITextBorderStyle.RoundedRect
newTextField.translatesAutoresizingMaskIntoConstraints = false
let leadingConstraint = NSLayoutConstraint(item: newTextField, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: nameTextField, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: newTextField, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: nameTextField, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)
newTextField.addConstraint(leadingConstraint)
newTextField.addConstraint(trailingConstraint)
view.addSubview(newTextField)
fieldCount++
positionY = positionY + 15 + newTextField.frame.size.height
}
}
不幸的是,上面的代码在运行时崩溃了。
最佳答案
您需要首先添加SubView,然后才添加约束。 您无法在不相关的 UIView 之间连接约束...
来自文档:
Discussion: The constraint must involve only views that are within scope of the receiving view. Specifically, any views involved must be either the receiving view itself, or a subview of the receiving view. Constraints that are added to a view are said to be held by that view. The coordinate system used when evaluating the constraint is the coordinate system of the view that holds the constraint.
关于ios - 以编程方式将现有约束复制到新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33423952/