ios - 以编程方式将现有约束复制到新对象

标签 ios swift constraints nslayoutconstraint

我允许用户在按下按钮时创建一个新的文本字段。我想以编程方式从现有文本字段复制前导和尾随约束。我的代码:

 @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/

相关文章:

ios - UIAlertController 改变了我的按钮颜色

ios - 如何在swift中制作虚线?

ios - 为什么DispatchGroup会干扰主队列?

ios - 删除 UISearchBar 文本字段周围的填充

swift - 如何根据通用类型在 Swift 中拥有默认和专用功能?

c# - 排除通用约束中的类型(可能?)

ios - 可以在 Objective-C 中保存种子 PRNG 吗?

postgresql - postgresql 检查约束的自定义错误消息

ios - 由于 Completion Handler,无法正确计算单元格高度

ios - 单击按钮时向图像添加阴影 - iOS Swift