Autolayout

2018-03-27  本文已影响12人  那位小姐

Autolayout的2个核心概念

与 Autoresizing 区别

代码实现Autolayout

代码实现Autolayout的步骤

- (void)addConstraint:(NSLayoutConstraint *)constraint;
- (void)addConstraints:(NSArray *)constraints;

代码实现Autolayout的注意点

NSLayoutConstraint

创建约束对象的常用方法

/*
view1 :要约束的控件
attr1 :约束的类型(做怎样的约束)
relation :与参照控件之间的关系
view2 :参照的控件
attr2 :约束的类型(做怎样的约束)
multiplier :乘数
c :常量
*/
+(id)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c;

添加约束的规则(1)

VFL语言

VFL示例

VFL的使用

/*
format :VFL语句
opts :约束类型
metrics :VFL语句中用到的具体数值
views :VFL语句中用到的控件
*/
+ (NSArray *)constraintsWithVisualFormat:(NSString *)format options:(NSLayoutFormatOptions)opts metrics:(NSDictionary *)metrics views:(NSDictionary *)views;

有了Autolayout的UILabel

UILabel实现包裹内容

基于Autolayout的动画

[UIView animateWithDuration:1.0 animations:

  ^{

    [添加了约束的view layoutIfNeeded];

}];

Masonry框架的使用示例

下载地址: https://github.com/SnapKit/Masonry

 //设置约束
 - (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *))block;

 //如果之前已经有约束,则更新新的约束,如果没有约束,则添加约束
 - (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *))block;

 //将之前的约束全部删除,添加新的约束
- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block;

以下为代码使用实现布局效果:
     //添加两个控件
     UIView *blueView = [[UIView alloc] init];
     blueView.backgroundColor = [UIColor blueColor];
     blueView.translatesAutoresizingMaskIntoConstraints = NO;
     [self.view addSubview:blueView];

     UIView *redView = [[UIView alloc] init];
     redView.backgroundColor = [UIColor redColor];
     redView.translatesAutoresizingMaskIntoConstraints = NO;
     [self.view addSubview:redView];

     //给蓝色View设置约束
     [blueView mas_makeConstraints:^(MASConstraintMaker *make) {
14         make.left.equalTo(self.view.mas_left).offset(30);//和父view的左边间距为30;
         make.bottom.equalTo(self.view.mas_bottom).offset(-30);//和父view的底部间距为30;
         make.right.equalTo(redView.mas_left).offset(-30);//和红色view的间距为30;
         make.height.mas_equalTo(50);//蓝色view的高度为50
     }];

     //给红色View设置约束
     [redView mas_makeConstraints:^(MASConstraintMaker *make) {
         make.right.equalTo(self.view.mas_right).offset(-30);//和父view的右边间距为30;
         make.bottom.equalTo(blueView.mas_bottom);//和蓝色view的底部对齐
         make.height.equalTo(blueView.mas_height);//和蓝色view的高度相等
         make.width.equalTo(blueView.mas_width);//和蓝色view的宽度相等
     }];

制作九宫格样式的视图布局

[图片上传失败...(image-738d9-1522131474260)]
[图片上传失败...(image-923fb8-1522131474260)]

上一篇 下一篇

猜你喜欢

热点阅读