Masonry詳解

- (void)viewDidLoad {

    [super viewDidLoad];

 

    //1.view1 居中顯示

    

    UIView *view1 = [[UIView alloc]init];

    view1.backgroundColor = [UIColor redColor];

    [self.view addSubview:view1];

    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {

        

        make.center.equalTo(self.view);  //居中

        make.size.mas_equalTo(CGSizeMake(300, 300));  //設置寬高

        //make.size.equalTo(@100);    //設置size

        //make.size.mas_equalTo(@100);



    }];

    

    

    //2.view2  在view1的正中間

    UIView *view2 = [UIView new];

    view2.backgroundColor = [UIColor blackColor];

    [view1 addSubview:view2];

    [view2 mas_makeConstraints:^(MASConstraintMaker *make) {

        

       // make.top.left.bottom.and.right.equalTo(view1).with.insets(UIEdgeInsetsMake(10, 10, 10, 10));



等價於:

//         make.top.equalTo(view1).with.offset(10);

//         make.left.equalTo(view1).with.offset(10);

//         make.bottom.equalTo(view1).with.offset(-10);

//         make.right.equalTo(view1).with.offset(-10);

//



也等價於:



        //設置四邊縮進20

        make.edges.equalTo(view1).with.insets(UIEdgeInsetsMake(20, 20, 20, 20));

//        make.size.width.equalTo(@200);

//        make.size.height.equalTo(@200);

//        

        

    }];

    

注意點:



    /*

     mas_makeConstraints 只負責新增約束 Autolayout不能同時存在兩條針對於同一對象的約束 不然會報錯

     mas_updateConstraints 針對上面的狀況 會更新在block中出現的約束 不會致使出現兩個相同約束的狀況

     mas_remakeConstraints 則會清除以前的全部約束 僅保留最新的約束

     

     

    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {

        

    }];

    

    [view1 mas_remakeConstraints:^(MASConstraintMaker *make) {

        

    }];

    [view1 mas_updateConstraints:^(MASConstraintMaker *make) {

        

        

    }];

     

     */

    



    //3.view3與view1 在同一列

    UIView *view3 = [UIView new];

    view3.backgroundColor = [UIColor greenColor];

    [self.view addSubview:view3];

    [view3 mas_makeConstraints:^(MASConstraintMaker *make) {

        

        make.size.mas_equalTo(CGSizeMake(100, 100));

        make.centerX.equalTo(view1);   //設置水平居中

        make.top.equalTo(view1.mas_bottom).with.offset(20);  //與上view的垂直間隔

        

        

    }];

 

    

 

}

 
相關文章
相關標籤/搜索