In addition to using storyboard, you can use code to dynamically add constraints to the specified UIView.
For example, there are two Uilabel:somelabel,otherlabel
First instantiate with code, two controls
Self.somelabel == = = no;[ Self.view AddSubview:self.inputContainerView];
Two points are important:
Translatesautoresizingmaskintoconstraints = NO Otherwise the layout will be chaotic
- Somelabel and Otherlabel must have Superview, or there will be a warning
The view hierarchy isn't prepared for the constraint
When added to a view, the constraint ' s items must is descendants of that view (or the view itself). This would crash if the constraint needs to being resolved before the view hierarchy is assembled.
Run time crash
Terminating app due to uncaught exception ' nsgenericexception ', Reason: ' Unable to install constraint on view. Does the constraint reference something from outside the subtree of the view? That ' s illegal
For example, a new category for UIView
One of the methods
-(nslayoutconstraint*) Verticaldistancetop: (uiview*) TopView constant: (cgfloat) constant{ Nslayoutconstraint*topconstrant = [Nslayoutconstraint constraintwithitem:self attribute:nslayoutattributetop Relatedby:nslayoutrelationequal Toitem:topview attribute:nslayoutattributebottom multiplier:1 Constant:constant]; return topconstrant;}
Returns a constraint that guarantees that the bottom distance of the self specific TopView is contant
Constraint constructor: Constraintwithitem, pay attention to the calculation formula:
VIEW1.ATTR1 = view2.attr2 * Multiplier + constant
/* Create constraints explicitly. Constraints is of the form "VIEW1.ATTR1 = view2.attr2 * multiplier + constant" */+ (instancetype) constr Aintwithitem: (IDID) view2 attribute: (nslayoutattribute) attr2 multiplier: (cgfloat) multiplier Constant: (cgfloat) C;
The method that makes the constraint effective after it is generated
Nslayoutconstraint*topconstraint = [Self.somelabel VerticalDistanceTop:self.otherLabel constant:]; = YES;
Constraint nslayoutconstraint for iOS dynamic management AutoLayout