Swift4问题:以编程方式更改Nslayoutconstraint

时间:2017-11-02 05:15:46

标签: ios nslayoutconstraint swift4

我想以编程方式将UITextfield txtAmount NSLayoutConstraint的位置从集合视图的顶部到底部更改为图像视图的底部。所有视图都嵌入在ui视图中。

将旧约束从故事板拖动并映射到视图控制器。 新约束constr将以编程方式创建。

在实施和执行方面,它说

When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled.
'Unable to install constraint on view.  Does the constraint reference something from outside the subtree of the view?  That's illegal. 

请您告诉我这些修改的指导方针吗?我将UI元素嵌入到嵌入式UIView中,因为我使用过scrollview。

    let constr = NSLayoutConstraint(item: txtAmount, attribute: .top, relatedBy: .equal, toItem: imageView, attribute: .bottom , multiplier: 1, constant: 0)

    IETypeList.removeFromSuperview()
    uiviewType.removeFromSuperview()

    txtAmount.addConstraint(constr)
    txtAmount.removeConstraint(constraintPo)

enter image description here

1 个答案:

答案 0 :(得分:0)

您要向txtAmount添加约束,而您应该将其添加到实际包含txtAmount的视图和此约束中引用的另一个视图,即imageView。我们将此视图命名为superview

let constr = NSLayoutConstraint(item: txtAmount, attribute: .top, relatedBy: .equal, toItem: imageView, attribute: .bottom , multiplier: 1, constant: 0)

IETypeList.removeFromSuperview()
uiviewType.removeFromSuperview()

txtAmount.removeConstraint(constraintPo)
superview.addConstraint(constr)

但是从iOS 8开始不推荐这种方式。正如docs所说,您应该将约束isActiveread this)属性设置为true,而不是iOS将它们添加到相关视图:

IETypeList.removeFromSuperview()
uiviewType.removeFromSuperview()

constraintPo.isActive = false
constr.isActive = true