First of all thanks to the support of many netizens, recently I was really too much, so did not write too much. But to see everyone's feedback and evaluation, I still have to insist on squeezing out time to share my experience. If you have any suggestions, comments or questions about what I have written, please leave a message on my blog:
Okay, here we are. The previous articles in this series explain the principles of automatic layout and how to add constraints. This article mainly introduces the following content:
- Some user controls have their own content dimension constraints
- View and Debug Program Interface view hierarchies, dimensions, and automatic layout constraints at run time using the View debugging tool
- Object associations that create constraints
- Implement the layout update of a view by modifying the constant value of the constraint, adding a new constraint by removing the old constraint, setting the constraint Activation property, setting the constraint priority, and so on
- Updating the interface layout with animations
The following is an example of a user login interface to explain. First, download the initial project:
Http://yunpan.cn/cQDIbjtf98zzV (Extract code: 3D6B)
Unzip and use Xcode to open the project, select any iphone emulator, compile the project and run it.
One, its own content size constraints
Back to Xcode open Main.storyboard, select the Avatar picture View head image, and open the Dimensions window (size Inspector, shortcut key??). 5) view its layout constraints.
You can see that the picture view currently has 2 constraints:
- The Horizontal center point is aligned with the horizontal center point of its parent view (determines the picture horizontal position x)
- The bottom is 20 points away from the top of the text control below (it is known that the vertical position of the text control below is OK, so it also determines the picture's vertical position y)
Wait, there seems to be a problem here. Careful readers may ask questions, and the first article in this series explicitly says that to determine the exact position of a view, you need at least 4 layout constraints (to determine the horizontal position x, vertical position y, Width w, and height h). The existing 2 constraints can only determine x and Y, and lack the necessary information to determine W and H. At this point, however, interface Builder does not indicate a lack of constraint errors (if the constraint is really missing, interface builder will display a red error circle and prompt missing Constraints), and the program is running normally with no error. What's going on here?
Note that some user controls for displaying content, such as text control Uilabel, button UIButton, picture View Uiimageview, and so on, have their own content dimensions (intrinsic content size). Such user controls add layout constraints based on their content dimensions. That is, if the developer does not explicitly give its width or height constraints, the self-content constraints it automatically adds will work. So seemingly "missing" constraints are actually not.
For Uiimageview, its own content size is the size of the picture (1 time times the image). Open Images.xcassets, select the 1x diagram in the head, and in the Properties window (Attribute Inspector) you can see its dimensions as 133px*133px.
We might as well use the interface-level debugging tools provided by Xcode to dynamically view information such as view hierarchies, dimensions, and layout constraints at run time. If you are not currently running the program, compile the run, then open the Debug Navigation window (Debug Navigator), click the Process View option button, select the interface hierarchy (view UI Hierarchy) to open the interface level debugging tool.
The view hierarchy, the view type (including system private type) and layout constraints are listed at the left of Xcode. The middle area displays a detailed view of the style, dimensions, levels, and so on, and you can drag the mouse around the space to see and debug the interface at different angles. The right side displays different properties based on the selection.
With Uiimageview selected, open the Dimensions window on the right, you can see 4 black constraints in the auto layout area, two of which define the width W as 133 points, the height H to 133 points, and the following (content size) to indicate that the constraint is its own content dimension constraint. The View debugging tool is helpful to solve the problem of automatic layout of the interface, when the problem is not known for some reason, it is advisable to use this tool debugging.
Of course, we can also use code to print out the automatic layout constraints of a view, which is also a common debugging tool. In Main.storyboard, select Head Image view and set its tag to 99 in the Properties window, and then add Viewdidappear in Viewcontroller.m: Method:
-(void) Viewdidappear: (BOOL) animated{ [Super viewdidappear:animated]; uiview* Headimageview = [Self.view viewwithtag:99]; For (nslayoutconstraint* Eachcon in headimageview.constraints) { NSLog (@ "\n%@\npriority:%f", Eachcon, eachcon.priority);} }
The output after the run is:
<nscontentsizelayoutconstraint:0x7aeda9e0 H:[head (133)] hug:251 compressionresistance:750 (names:head:0 x7af84130) >priority:1000.000000<nscontentsizelayoutconstraint:0x7aedab30 V:[head (133)] Hug:251 compressionresistance:750 (names:head:0x7af84130) >priority:1000.000000
You can see that each constraint printed is described using the VFL language.
(think, could you put the above code in the Viewdidappear: method instead of the Viewdidload method?) Why? )
If the developer explicitly gives the width and height constraints, the explicit constraint will prevail. Select Head Image view and add a constraint with a width of 120 points, a height of 120 points, recompile the run program, and the View debugging tool displays its layout constraints as:
Where its own content size constraint is gray, indicating that it does not work. At the same time the console output is:
<NSLAYOUTCONSTRAINT:0X7C189AC0 H:[head ( names:head:0x7c1897a0) >Priority:1000.000000< Nslayoutconstraint:0x7c189af0 V:[head ( names:head:0x7c1897a0) >Priority:1000.000000< Nscontentsizelayoutconstraint:0x7bea62a0 H:[head (133)] hug:251 compressionresistance:750 (names:head:0 X7C1897A0) >priority:1000.000000<nscontentsizelayoutconstraint:0x7bea63f0 V:[head (133)] Hug:251 compressionresistance:750 (names:head:0x7c1897a0) >priority:1000.000000
Second, create the Constraint object association and modify the constraint
Our user login app has a less-than-good user experience, which means that when entering a username and password, the keyboard obscures the text input box and the login button:
We need to update the interface layout when the keyboard pops up or back up, there are several ways to update the interface layout:
- To modify the constant value of a constraint
- Set constraint activation properties (delete old constraint and add new constraint)
- To adjust the precedence of a constraint
You can use the first method to directly modify the constant value of a constraint when you only need to pan the position of the view to resolve the problem. The simplest and most efficient way to do this, but not all of them, can be used in the latter two ways.
1. modifying constraint constant values
For this app, the vertical position of all controls is based on the vertical position of the text control in the center. We intend that when the keyboard does not pop up, the vertical spacing of the top Layout guide of the Text control is (label.top = 250), and the spacing is reduced to 0 (label.top = 0) when the keyboard pops up.
Interface Builder allows us not only to create Iboutlet object associations for view objects, but also to create object associations for constrained objects so that a constraint can be accessed and modified through code.
Back to Xcode open Main.storyboard, select the text control user Name and Pwd Label, click the top constraint Blue line in the Dimensions window on the right, and double-click the top Space to:top Layout guide constraint below:
The Project window at the left highlights the constraint. Switch to the Assistant editor, confirm that VIEWCONTROLLER.M is open in the right window, and then select the constraint and press and hold the key to drag to the class extension area of the Viewcontroller class on the right, and name it usernamepwdlabeltopcons in the pop-up window. , clicking the Connect button creates an object association for the constraint object, similar to the object association that creates the view.
Next, the Viewcontroller class needs to respond to keyboard popup and retract events, adding the following code to the Viewdidload method of the Viewcontroller class:
[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (keyboardwillshow:) Name: Uikeyboardwillshownotification Object:nil]; [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (keyboardwillhide:) Name: Uikeyboardwillhidenotification Object:nil];
Uikeyboardwillshownotification and uikeyboardwillhidenotification These two notification messages will be thrown when the keyboard is about to eject and the keyboard is about to retract, and we can keyboardwillshow: and keyboardwillhide: Modify the Usernamepwdlabeltopcons constraint in both methods.
Note that there are several important properties for the constraint:
/* Accessors Firstitem.firstattribute {==,<=,>=} seconditem.secondattribute * Multiplier + constant */@property ( ReadOnly, assign) ID FirstItem; @property (readonly) Nslayoutattribute FirstAttribute; @property (readonly) Nslayoutrelation relation; @property (readonly, assign) ID SecondItem; @property (readonly) Nslayoutattribute Secondattribute; @property (readonly) CGFloat multiplier;/* Unlike the other properties, the constant could be modified after Constraint creation. Setting the constant on an existing constraint performs much better than removing the constraint and adding a new one ' s just like the old and for have a new constant. */@property CGFloat constant;
When you use code to modify a constraint, you can only modify the constant value of the constraint constant. Once a constraint is created, other read-only properties cannot be modified, especially if the scale factor multiplier is also read-only.
Then add the following code to the Viewcontroller class:
-(void) Keyboardwillshow: (nsnotification *) notification{ //When the keyboard pops up, the vertical spacing from top Layout guide is 0 Self.userNamePwdLabelTopCons.constant = 0.0f;} -(void) Keyboardwillhide: (nsnotification *) notification{ //When the keyboard does not pop up, the vertical spacing from top Layout guide of the text control is Self.userNamePwdLabelTopCons.constant = 250.0f;} -(void) dealloc{ [[Nsnotificationcenter Defaultcenter] removeobserver:self];}
Don't forget to remove the keyboard event listener from the Dealloc method. Compile and run the program, click the text input box, this time the keyboard pop-up, because the text control moved up, the position of all the interface controls are moved up, will not be blocked by the keyboard.
Because the Viewcontroller class overrides the touch screen method and cancels the first responder state of the text input box, clicking outside the text input box will remove the keyboard and revert to the original layout state.
#pragma mark-touch event handler-(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event{ [Super Touchesbegan:touches Withevent:event]; [Self.usernametextfield Resignfirstresponder]; [Self.userpwdtextfield Resignfirstresponder];}
2. Modify the constraint Activation property, or delete the old constraint and add a new constraint
Now we're going to layout the interface: When the keyboard doesn't pop up, the text control's vertical center is the same as its parent view (Label.centery = Superview.centery); When the keyboard pops up, the vertical center of the text control is 0.6 times times the vertical center of its parent view (Label.centery = 0.6 * superview.centery).
For this example, we can fix the problem by modifying the constant value of a constraint. But this time it's different. The scale factor is read-only and cannot be modified after the constraint is created. So in this case, we can't modify a constraint, we need to remove the unnecessary constraints, and then add a new constraint.
In Main.storyboard, in the left View Hierarchy window, select the constraint of the text control distance top Layout Guide Vertical Space-(+)-User Name and Pwd label-top Layout Gui De, and then press the DELETE key to delete the constraint.
Then select the text control user Name and Pwd Label, click the Align menu, tick the vertical Center in container and take the value 0, click the Add 1 Constraint button. This causes the text control to be centered vertically.
Repeat the steps in to create a constraint vertically centered on the text control again. Select the text control user Name and Pwd Label, click the vertical center constraint Blue Line in the right dimension window, and the two vertical centering constraints we created just below are listed below.
Double-click the Align Center Y to:superview constraint above to make sure that first item is User Name and Pwd label.center y,second item is Superview.center Y. If not, click the first item or the Second item drop-down menu, select Reverse First and Second item, and swap the first item with the Second item (the relative and inverse functions described in the second article in this series). Then, in the right dimension window, change the value of multiplier from 1 to 0.6:
Interface Builder will get an error after the change because the two constraints we just added are conflicting (label.centery = superview.centery && label.centery = 0.6 * Superview.centery, this cannot be met at the same time).
Click the red arrow above the View Hierarchy window and Interface Builder lists the two conflicting constraints. Select a constraint, and the Right dimension window lists the details of the constraint. We checked the constraint of multiplier to 0.6 and then uncheck the installed box below the right size window.
The value of the installed box corresponds to the value of the active property of the constrained object, that is, whether the constraint is active, tick indicates the active state (active state, yes), no tick indicates the inactive state (invalid state, active property is no). Now the constraint that multiplier is 0.6 is no longer in effect, so there is no constraint conflict.
Then follow the method described above, add the above two constraints of the object Association, multiplier to 1 of the constraints named Labelcenterynormalcons, The constraint for multiplier 0.6 is named Labelcenterykeyboardcons, and storage is set to strong:
This is due to the need to dynamically add or remove constraints to the view, so make sure to use strong references to ensure that the constrained objects are not recycled.
Then modify Keyboardwillshow: With Keyboardwillhide: Method:
-(void) Keyboardwillshow: (nsnotification *) notification{ self.labelCenterYNormalCons.active = NO; self.labelCenterYKeyboardCons.active = YES;} -(void) Keyboardwillhide: (nsnotification *) notification{ self.labelCenterYKeyboardCons.active = NO; self.labelCenterYNormalCons.active = YES;}
Note that it is possible to set a constraint that requires active to no, and then set a constraint that requires active to Yes, which could cause a run-time constraint error if the above two statements are reversed. Also, because the active property is the newly added property of the iOS 8 SDK, for iOS 6 and iOS 7, you need to call AddConstraint: With Removeconstraint: Method. Compile run
3. Adjust the precedence of different constraints
An example of this is the adjustment of the interface layout by adjusting the active properties of the different constraints (by deleting the old additions). There is another way that is important, which is to adjust the precedence of different constraints.
Each constraint will have a priority, corresponding to the Nslayoutconstraint object's Precedence property:
@interface nslayoutconstraint:nsobject....../* If A constraint ' s priority level was less than uilayoutpriorityrequired, t Hen it is optional. Higher priority constraints is met before lower priority constraints. Constraint satisfaction is not any or nothing. If a constraint ' a = = B ' is optional, that means we'll attempt to minimize ' abs (A-c) '. The modified as part of the initial set up. An exception'll be thrown if it's set after a constraint have been added to a view. */@property uilayoutpriority priority, ... @end
The priority is a floating-point value that ranges from 1 (lowest) to 1000 (highest). Some of the commonly used priority values are defined by aliases:
typedef float Uilayoutpriority;static Const uilayoutpriority uilayoutpriorityrequired ns_available_ios (6_0) = 1000; A required constraint. Do not exceed This.static const uilayoutpriority Uilayoutprioritydefaulthigh ns_available_ios (6_0) = 750; This is the priority level with which a button resists compressing its content.static const uilayoutpriority UILAYOUTPR Ioritydefaultlow Ns_available_ios (6_0) = 250; This was the priority level at which a button hugs its contents horizontally.static const uilayoutpriority Uilayoutprior Ityfittingsizelevel Ns_available_ios (6_0) = 50;
A constraint with a priority of uilayoutpriorityrequired is mandatory (Required Constraint), which is a constraint that must be met, and a constraint with a priority of less than 1000 is an optional constraint (Optional Constraint). The default is to create a mandatory constraint.
After you use automatic layout, the specific location and dimensions of a view may be determined by multiple constraints. These constraints lay out the view in order of precedence from highest to lowest, that is, the views prioritize high-priority constraints, and then meet low-priority constraints.
For the above example, we have created two conflicting constraints, namely Label.centery = superview.centery && label.centery = 0.6 * superview.centery. There is a conflict because both have the same priority and are 1000. However, if one of the priorities is lowered, then there will be no conflict, because the higher precedence constraint will work first.
When you open Main.storyboard, the installed marquee with the multiplier constraint of 0.6 is ticked, and a layout conflict occurs again. Then set its priority to 250 in the right dimension window, at which point the layout conflict disappears and notice that the Blue line representing the constraint in the interface becomes dashed, indicating that this is an optional constraint with a lower precedence.
In the same way, set the additional vertical center constraint for the multiplier to 1 with the priority of 750.
Then keyboardwillshow: and Keyboardwillhide: The method is modified as follows:
-(void) Keyboardwillshow: (nsnotification *) notification{ self.labelCenterYNormalCons.priority = Uilayoutprioritydefaultlow; self.labelCenterYKeyboardCons.priority = Uilayoutprioritydefaulthigh;} -(void) Keyboardwillhide: (nsnotification *) notification{ self.labelCenterYKeyboardCons.priority = Uilayoutprioritydefaultlow; self.labelCenterYNormalCons.priority = Uilayoutprioritydefaulthigh;}
Recompile to run with the same effect.
It is important to note that you can only modify the precedence of an optional constraint, which means:
- Changing the priority from a value less than 1000 to 1000 is not allowed
- Changing the priority from 1000 to a value less than 1000 is not allowed
For example, if you change the priority from 250 to 1000, an exception is thrown:
Terminating app due to uncaught exception ' nsinternalinconsistencyexception ', Reason: ' Mutating a-priority from Requir Installed constraint (or VICE-VERSA) is not supported. You passed priority and the existing is 250. '
This is why the two constraints are set to 750 and 250, respectively, in storyboard.
4. Updating the interface layout with animations
Because the modified constraint takes effect immediately, when the keyboard pops up or retracts, the change in the position of the control appears very stiff. We might as well use animations to update the interface layout by calling the static animation method of UIView and calling the Layoutifneeded method in the animation block code body to the view object that needs to update the constraint. To Keyboardwillshow: and Keyboardwillhide: The end of the method, insert the following code:
[UIView animatewithduration:0.25f animations:^ { [Self.view layoutifneeded]; }];
The process of re-compiling is very natural because of the animation used to re-layout the interface.
Third, the spring effect of its own content size
Not to be continued ...
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
IOS 8 Auto Layout Interface Series 5-Self content dimension constraints, modify constraints, layout animations