AutoLayout Frame Masonry Usage experience

Source: Internet
Author: User

AutoLayout Frame Masonry Usage experience

Some basic concepts of AutoLayout

    • Using constraints to control the size and position of the view, the system will calculate the frame redraw screen at run time by setting constraints
    • Two properties Content Compression resistance (crowding, higher value is fixed) and content hugging (hug), masonry code is as follows
//content hugging 为1000[view setContentHuggingPriority:UILayoutPriorityRequired                           forAxis:UILayoutConstraintAxisHorizontal];//content compression 为250[view setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
    • The Multipler property indicates that the constraint value is a percentage of the constrained object, and there is a corresponding Multipliedby function in the masonry.
//宽度为superView宽度的20%make.width.equalTo(superView.mas_width).multipliedBy(0.2);
    • AutoLayout Uilabel Set the multi-line calculation needs to set Preferredmaxlayoutwidth
label.preferredMaxWidth = [UIScreen mainScreen].bounds.size.width - margin - padding;
    • Preferredmaxlayoutwidth used to make the largest width, generally used in multi-line Uilabel
    • Systemlayoutsizefittingsize method to get the height of the view
    • IOS7 has two very useful properties, Toplayoutguide and Bottomlayoutguide, This two is primarily for easy access to the Head view area and the bottom view area of the Uinavigationcontroller and Uitabbarcontroller.
//Masonry直接支持这个属性make.top.equalTo(self.mas_topLayoutGuide);
AutoLayout differences on several methods of updating
    • Setneedslayout: Tells the page to be updated, but does not start the update immediately. Layoutsubviews is called immediately after execution.
    • layoutifneeded: Tells the page layout to be updated immediately. So the general will be used with setneedslayout. If you want to call this method to generate a new frame immediately, use this general layout animation to make the animation take effect directly after the layout is updated.
    • Layoutsubviews: System Rewrite layout
    • Setneedsupdateconstraints: Notifies you of the need to update the constraint, but does not start immediately
    • updateconstraintsifneeded: Notify update constraint immediately
    • Updateconstraints: System Update constraint
Masonry precautions for use
    • With mas_makeconstraints, the view needs to be addsubview to use this method.
    • Mas_equalto for numeric elements, Equalto for multiple attributes such as Make.left.and.right.equalTo (Self.view)
    • Methods and and with are only for readability, and returning themselves, such as Make.left.and.right.equalTo (Self.view) and Make.left.right.equalTo (Self.view), are the same.
    • Because iOS is in the upper-left corner, be aware that right and bottom use negative numbers when using offset.
Masonry problems needing attention when fitting iOS6 and iOS7

The development of the project is done on the IOS8 debugging, the test found that the low version of the system will be a crash phenomenon, repair after the summary of the problem is mainly in the equalto of the parent view or the parent view sibling of the child view caused by the object, So when it comes to constraint, if there's a crash problem, 90% is because of this.

Masonry Use example basic notation
10 relative to the parent view marginUiedgeinsets padding =Uiedgeinsetsmake (10,10,10,10); [Self.avatarview mas_makeconstraints:^ (Masconstraintmaker *make) {make.top.equalTo (superview.mas_top). With.offset (Padding.top);A optional semantic filler make.Left.equalto (Superview.mas_left). With.offset (padding.left); Make.bottom.equalTo (Superview.mas_bottom). With.offset (-padding.bottom); Make.Right.equalto (superview.mas_right). With.offset (-padding.right);}];10 concise notation relative to the parent view margin [Self.avatarview mas_makeconstraints:^ (Masconstraintmaker *make) {make.edges.equalTo (Superview). With.insets (padding);}];The two functions are exactly the same [Self.avatarview mas_makeconstraints:^ (Masconstraintmaker *make) {make.Left.greaterthanorequalto (Self.view); Make.Left.greaterthanorequalto (Self.view.mas_left);}];. Equalto. Lessthanorequalto. Greaterthanorequalto using nsnumber[Self.avatarview mas_makeconstraints:^ (Masconstraintmaker *make) {Make.width.greaterThanOrEqualTo (@200); Make.width.lessThanOrEqualTo (@400); Make.Left.lessthanorequalto (@10);}];If you can use the previous data structure without nsnumber, just use the Mas_equalto on the line [Self.avatarview mas_makeconstraints:^ (Masconstraintmaker *make) {make.top.mas_equalTo (42); Make.height.mas_equalTo (20); Make.size.mas_equalTo (Cgsizemake (50,100)); Make.edges.mas_equalTo (Uiedgeinsetsmake (10,0,10,0)); Make.Left.mas_equalto (Self.view). Mas_offset (Uiedgeinsetsmake (10,0,10,0);}];You can also use an array [Self.avatarview mas_makeconstraints:^ (Masconstraintmaker *make) {make.height.equalTo (@[Self.view.mas_height, Superview.mas_height]); Make.height.equalTo (@[Self.view, Superview]); Make.Left.equalto (@[Self.view, @(Superview.mas_right]);}];Use of priority [Self.avatarview mas_makeconstraints:^ (Masconstraintmaker *make) {make.Left.greaterthanorequalto (Self.view.mas_left). With.prioritylow (); Make.top.equalTo (self.view.mas_top). With.priority (600);}];Create multiple constraints at the same time [Self.avatarview mas_makeconstraints:^ (Masconstraintmaker *make) {Let Top,left,bottom,right and Self.view the same make.edges.equalTo (Self.view);Edges Make.edges.equalTo (Self.view). Insets (Uiedgeinsetsmake (5, 10, 15, 20)); //size make.size.greaterThanOrEqualTo (self.view); Make.size.equalTo (Superview). Sizeoffset (cgsizemake (100,-< Span class= "Hljs-number" >50)); //center make.center.equalTo (self.view); Make.center.equalTo (self.view) centeroffset (cgpointmake (-< Span class= "Hljs-number" >5, 10)); //chain make. left. right.and.bottom.equalto (self.view); Make.top.equalTo ( Span class= "Hljs-keyword" >self.view);}];            
AutoLayout situation how to calculate the height of UITableView

The main is the height of the Uilabel will change, so here is the main point is to say how to handle label changes, set Uilabel when the attention to set preferredmaxlayoutwidth this width, and contenthuggingpriority for Uilayoutpriorityrequried

CGFloat maxWidth = [UIScreen Mainscreen]. Bounds. Size. Width-10 *2;textlabel = [UILabel New];textlabel. NumberOfLines =0;textlabel. preferredmaxlayoutwidth = MaxWidth; [Self. Contentview Addsubview:textlabel]; [Textlabel mas_makeconstraints:^ (Masconstraintmaker *make) {Make. Top. Equalto (Statusview. Mas_bottom). With. Offset (10); Make. Left. Equalto (self.contentview) .with.offset (10); Make.right.equalto (self.contentview) .with.offset (-10); make .bottom.equalto (self.contentview) .with.offset (-10);}]; [_contentlabel setcontenthuggingpriority:uilayoutpriorityrequired ForAxis:uilayoutconstraintaxisvertical];           

If the version supports a minimum version of iOS 8 or more, you can directly return to the TableView Heightforrowatindexpath using Uitableviewautomaticdimension.

tableView.rowHeight = UITableViewAutomaticDimension;tableView.estimatedRowHeight = 80; //减少第一次计算量,iOS7后支持- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { // 只用返回这个! return UITableViewAutomaticDimension;}

But if you need to be compatible with iOS 8 before, it will be back to the old way, mainly with systemlayoutsizefittingsize to get high. The step is to first add a height property to the data model to cache the high, then static a cell instance initialized only once in the table view's Heightforrowatindexpath proxy and populate the data based on the model content. Finally, the cell's height is obtained according to the Systemlayoutsizefittingsize method of the cell's contentview. The specific code is as follows

Adding a property cache height to the model@interfaceDatamodel:NSObject@property (Copynonatomic)NSString *text;@property (Assignnonatomic)CGFloat cellheight;Cache height@end-(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) Indexpath {Static Customcell *cell;Initialize cell only onceStaticdispatch_once_t Oncetoken;Dispatch_once (&oncetoken, ^{cell = [TableView dequeuereusablecellwithidentifier:Nsstringfromclass ([Customcell class])]; }); Datamodel *model = self. dataarray[(nsuinteger) Indexpath. row]; [Cell Makeupdata:model]; if (model. Cellheight <= 0) { //use systemlayoutsizefittingsize to get the height model. cellheight = [cell. Contentview systemlayoutsizefittingsize:uilayoutfittingcompressedsize]. Height + 1;} return model. Cellheight;}               
Animation

Because the layout constraints are to be removed from the frame this way of expression, but the animation is to be executed according to this, there will be some contradictions, but according to the principle of the layout constraints mentioned above, at some point the constraint will be reverted to frame so that the view display, This moment can be controlled by layoutifneeded this method. The specific code is as follows

[Aniview mas_makeconstraints:^(Masconstraintmaker *make) {Make.top.bottom.left.right.equalTo(self.view). Offset(ten);}] ; [aniview mas_updateconstraints:^(masconstraintmaker *make) {make.top.equalTo(self.view) . Offset(+);}] ; [UIView animatewithduration:3 animations:^{ [self.view layoutifneeded];}] ; 

AutoLayout Frame Masonry Usage experience

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.