Where to pay attention to the use of masonry

Source: Internet
Author: User

The most important thing about automatic layout is constraints : Mathematical expressions of relationships between UI elements. Constraints include dimensions, relative positions that are managed by priority and threshold values. They are additives that can lead to constraint collisions and insufficient constraints to determine the layout. Both of these situations can produce anomalies.

before use: AutoLayout differences about several methods of updating
    • setNeedsLayout: Notifies the page that an update is required, but does not start 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: Tells you to update the constraint, but does not start immediately
    • updateConstraintsIfNeeded: Informs you to update the constraint immediately
    • updateConstraints: System Update constraint
Use

1. Basic use

    • mas_makeConstraints: Adding a constraint
    • mas_updateConstraints: Update constraint, add new constraint Also
    • mas_remakeConstraints: Resets the previous constraint

    • multiplerThe attribute represents the multiplicative factor of the constraint object, which represents the constraint dividedBy value as a factor for the constraint object, and can be used to set view the aspect ratio

 //the adaptation of the screen, often depending on the width of the screen to fit a corresponding height, it is recommended to use the following constraints for the control of the adaptation
Span style= "FONT-SIZE:16PX;" >    [Self.topview AddSubview:self.topInnerView];
    [Self.topinnerview mas_makeconstraints:^ ( Masconstraintmaker *make) {
        Make.height.equalTo (self.topView.mas_height). Dividedby (3);
        Make.width.and.height.lessThanOrEqualTo (Self.topview);
        Make.width.and.height.equalTo ( Self.topview). With.prioritylow ();
        Make.center.equalTo (Self.topview) ;
   }];

    • Prioritylow () set constraint precedence
    • #define MAS_SHORTHAND_GLOBALS uses global macro definitions to make Equalto equivalent to mas_equalto
    • #define Mas_shorthand uses global macro definitions, which can be used without the MAS when calling the masonry method _ prefix
//Here you notice a place where this global macro definition is used , found that there can be a class ' nsarray+masadditions.h ', looked after the discovery can be self//can be in Updateconstraints method-(void) updateconstraints {[ Span class= "Hljs-keyword" >self.buttonviews updateconstraints:^ (MASConstraintMaker * Make) {Make.baseline.equalto ( self.mas_centery) .with.offset (self.offset);}]; [super updateconstraints];}          

To modify a view constraint dynamically:

// 创建视图约束[blueView mas_makeConstraints:^(MASConstraintMaker *make) {      self.animatableConstraint = make.edges.equalTo(superview).insets(paddingInsets).priorityLow();]];// 更改约束 (另一处方法中)UIEdgeInsets paddingInsets = UIEdgeInsetsMake(padding, padding, padding, padding);self.animatableConstraint.insets = paddingInsets;[self layoutIfNeeded];
    • debug mode:
      //add a key value to a view Greenview.mas_key = @ " Greenview "; //or in the following order Masattachkeys (Greenview, Redview, Blueview, Superview); //the same for each constraint can also be added keymake.height.greaterThanOrEqualTo (@5000) . Key (@ "Constantconstraint");         
    • preferredmaxlayoutwidth : Constraints on multiline labels
/ /confirmed position //confirm the Layoutsubviews value of the label in Preferredmaxlayoutwidth-( void) layoutsubviews {[super layoutsubviews]; //you have to call after [Super Layoutsubviews], Longlabel frame has value after setting preferredmaxlayoutwidth self.longlabel.preferredMaxLayoutWidth = Span class= "Hljs-keyword" >self.frame.size.width-100; //set preferredlayoutwidth, you need to re-layout [super layoutSubviews];}   
    • scrollViewProblem with constraints: the principle is to constrain the size of the ScrollView contentsize by a contentview, that is, to control the size of the parent view in terms of the child control's constraints
1. Control ScrollView Size (display area) [self.scrollview makeconstraints:^ (MASConstraintMaker * Make) {Make.edges.equalto ( Self.view);}]; //2. Add a Contentview to ScrollView, and add a constraint [Contentview makeconstraints:^ ( Masconstraintmaker *make) {make.edges.equalTo (self.scrollview); //notice the width constraint here, the constraint of this width is greater than the Add item Make.width.equalto (self.scrollview);}]; //3. To constrain the Contentview's child controls to a size that can control the Contentview       
    • New method: 2 or more than 2 controls, such as interval sorting
/** * Multiple controls are arranged at constant intervals, changing the length of the control or width value * * @param axistype Axis direction * @param fixedspacing interval size * @param leadspacing Head interval * @param tailspacing tail interval */-(void) Mas_distributeviewsalongaxis: (masaxistype) Axistype withfixedspacing: (cgfloat) fixedspacing L eadspacing: (cgfloat) leadspacing tailspacing: (cgfloat) tailspacing; /** * Multiple fixed-size controls are arranged in equal intervals, changing the gap of the interval * * @param axistype Axis direction * @param fixeditemlength The fixed length or width value of each control * @param leadspacing Head interval * @param tailspacing trailing interval */-(void) Mas_distributeviewsalongaxis: (masaxistype) Axistype withfixeditemlength: ( cgfloat) fixeditemlength leadspacing: (cgfloat) leadspacing tailspacing: (cgfloat) tailspacing;   

The use of the method is simple because it is a class extension of Nsarray:

//  创建水平排列图标 arr中放置了2个或连个以上的初始化后的控件//  alongAxis 轴线方向   固定间隔     头部间隔      尾部间隔[arr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:20 leadSpacing:5 tailSpacing:5];[arr makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(@60); make.height.equalTo(@60);}];

2. Precautions

    • Constrained view objects can be added to a view only after they have been addSubview
    • When all of your constraints are updateConstraints called inside, you need to call this method here, because updateConstraints the method needs to be triggered
Called inside the View instead of viewcontroller+ (BOOL) Requiresconstraintbasedlayout {ReturnYES;}/** * Apple recommended constraint additions and modifications put in this method species */-(void) Updateconstraints {[Self. Growingbutton updateconstraints:^ (Masconstraintmaker *make) {make. Center. Equalto (self); Make.width.equalto (@ (self< Span class= "hljs-variable" >.buttonsize.width)) .height.equalto (@ (self< Span class= "hljs-variable" >.buttonsize.height)) .width.lessthanorequalto ( self); Make.height.lessthanorequalto ( self); }]; //finally remembers the callback super method [super updateconstraints];}     
    • If you want to animate after you constrain the transformation, you need to do the following
// 通知需要更新约束,但是不立即执行[self setNeedsUpdateConstraints];// 立即更新约束,以执行动态变换// update constraints now so we can animate the change[self updateConstraintsIfNeeded];// 执行动画效果, 设置动画时间[UIView animateWithDuration:0.4 animations:^{ [self layoutIfNeeded];}];
automatic calculation of UITableViewCell height

It is recommended to use a library Uitableview-fdtemplatelayoutcell

Idea: The dynamic height of the cell, what are the main points of concern?

    • Viewcontroller itself does not need to know the type of cell
    • The cell height is not related to Viewcontroller, and the cell's height is determined by the cell itself.
    • What Viewcontroller really do is a

Here's the excerpt.

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;}               

Where to pay attention to the use of masonry

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.