简体   繁体   中英

Swift4 issues : change Nslayoutconstraint programmatically

I would like to change position of UITextfield txtAmount NSLayoutConstraint programmatically from its top to bottom of collection view to bottom of image view. All views are embed in a ui view.

Old constraint is dragged and mapped from storyboard to view controller. New constraint constr is to be created programmatically.

When it comes to implementation and execution, it says

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. 

Would you please tell me any guidelines for such modification ? I embed the UI elements in an embedded UIView because of scrollview I have used.

    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)

在此处输入图片说明

you are adding constraint to the txtAmount whereas you should've added it to the view which actually contains txtAmount and another view referenced in this constraint, ie imageView . Let's name this view which contains them 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)

But this is not recommended way since iOS 8. As the docs say, you should set the constraint isActive ( read this ) property to true instead, and iOS will add them to relevant views:

IETypeList.removeFromSuperview()
uiviewType.removeFromSuperview()

constraintPo.isActive = false
constr.isActive = true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM