ios - Adjusting constraints programmatically do they need to be first removed and then re-added? -
i have function in code adjust layout of buttons. called when .hidden set.
private func layoutbuttons() { redbutton.hidden = !redbuttonenabled redbuttonlabel.hidden = !redbuttonenabled yellowbutton.hidden = !yellowbuttonenabled yellowbuttonlabel.hidden = !yellowbuttonenabled removeconstraint(yellowbuttontrailingcontraint) if yellowbuttonenabled && !redbuttonenabled { yellowbuttontrailingcontraint = nslayoutconstraint(item: yellowbutton, attribute: .trailing, relatedby: .equal, toitem: self, attribute: .trailing, multiplier: 1.0, constant: -horizontalmargin) } else { yellowbuttontrailingcontraint = nslayoutconstraint(item: yellowbutton, attribute: .trailing, relatedby: .equal, toitem: redbutton, attribute: .leading, multiplier: 1.0, constant: -horizontalmargin) } addconstraint(yellowbuttontrailingcontraint) }
is necessary first remove constraint before changing , re-add afterwards have done above? saw in example somewhere seems bit odd. pointers on appreciated. thanks!
yes, removing constraint option, not necessary.
you can edit constraint changing constant value, update layout. example :
var constraintheight = nslayoutconstraint(item: someview, attribute: .height, relatedby:.equal, toitem:nil, attribute: .notanattribute, multiplier: 1.0, constant: 100) someview.addconstraint(constraintheight) ... //the constraint can edited later changing constant value constraintheight.constant = 200 someview.layoutifneeded()
or can activate or deactivate them, example :
var constraintheight1 = nslayoutconstraint(item: someview, attribute: .height, relatedby:.equal, toitem:nil, attribute: .notanattribute, multiplier: 1.0, constant: 100) var constraintheight2 = nslayoutconstraint(item: someview, attribute: .height, relatedby:.equal, toitem:nil, attribute: .notanattribute, multiplier: 1.0, constant: 200) constraintheight1.active = true constraintheight2.active = false someview.addconstraint(constraintheight1) someview.addconstraint(constraintheight2) ... //later can set other constraint active constraintheight1.active = false constraintheight2.active = true someview.layoutifneeded()
at given point active constraints used decide final layout of view. so, have few alternatives, have make sure never 2 conflicting constraints active, or else app crash. have remove 1 of conflicting constraints or deactivate it. hope helps :]
Comments
Post a Comment