ios - How to update swift Layout Anchors? -
trying find solution update multiple constraints multiple ui elements on event. have seen examples of deactivating, making change, reactivating constraints, method seems impractical 24 anchors working with.
one of sets of changes:
ticketcontainer.translatesautoresizingmaskintoconstraints = false ticketcontainer.topanchor.constraintequaltoanchor(self.topanchor).active = true ticketcontainer.leftanchor.constraintequaltoanchor(self.rightanchor, constant: 20).active = true ticketcontainer.widthanchor.constraintequaltoconstant(200.0).active = true ticketcontainer.leftanchor.constraintequaltoanchor(self.leftanchor, constant: 20).active = true ticketcontainer.widthanchor.constraintequaltoconstant(100.0).active = true
have tried saving relevant constraints created using layout anchors properties, , changing constant? e.g.
var tickettop : nslayoutconstraint? func setup() { tickettop = ticketcontainer.topanchor.constraintequaltoanchor(self.topanchor, constant:100) tickettop.active = true } func update() { tickettop?.constant = 25 }
possibly more elegant
depending on taste writing extensions, here possibly more elegant approach doesn't use properties, instead creates extension methods on nslayoutanchor
, uiview
aid in more succinct usage.
first write extension on nslayoutanchor
this:
extension nslayoutanchor { func constraintequaltoanchor(anchor: nslayoutanchor!, constant:cgfloat, identifier:string) -> nslayoutconstraint! { let constraint = self.constraintequaltoanchor(anchor, constant:constant) constraint.identifier = identifier return constraint } }
this extension allows set identifier on constraint in same method call creates anchor. note apple documentation implies xaxis anchors (left, right, leading, etc.) won't let create constraint yaxis anchors (top, bottom, etc.), don't observe true. if did want type of compiler checking, need write separate extensions nslayoutxaxisanchor
, nslayoutyaxisanchor
, , nslayoutdimension
(for width , height constraints) enforce same-axis anchor type requirement.
next write extension on uiview
constraint identifier:
extension uiview { func constraint(withidentifier:string) -> nslayoutconstraint? { return self.constraints.filter{ $0.identifier == withidentifier }.first } }
with these extensions in place, code becomes:
func setup() { ticketcontainer.topanchor.constraintequaltoanchor(self.topanchor, constant:100, identifier:"tickettop").active = true } func update() { self.constraint(withidentifier:"tickettop")?.constant = 25 }
note using constants or enum instead of magic string names identifiers improvement on above, i'm keeping answer brief , focused.
Comments
Post a Comment