iOS AutoLayout 简单运用(纯代码)

来源:互联网 发布:js 正则 可有可无 编辑:程序博客网 时间:2024/05/19 02:03

举例说明:创建一个grayView(宽150 高100 距上200 距左100

方法一:原生API 

    UIView *grayView = [UIView new];    grayView.backgroundColor = [UIColor lightGrayColor];    // 禁止将 autoresizingmask 转换为 constraints    grayView.translatesAutoresizingMaskIntoConstraints = NO;    [self.view addSubview:grayView];        // 添加 width 约束    NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:grayView attribute:(NSLayoutAttributeWidth) relatedBy:(NSLayoutRelationEqual) toItem:nil attribute:(NSLayoutAttributeNotAnAttribute) multiplier:0.0 constant:150];    // 添加 height 约束    NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:grayView attribute:(NSLayoutAttributeHeight) relatedBy:(NSLayoutRelationEqual) toItem:nil attribute:(NSLayoutAttributeNotAnAttribute) multiplier:0.0 constant:100];    // 添加 left 约束    NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:grayView attribute:(NSLayoutAttributeLeft) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:(NSLayoutAttributeLeft) multiplier:1.0 constant:100];    // 添加 top 约束    NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:grayView attribute:(NSLayoutAttributeTop) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:(NSLayoutAttributeTop) multiplier:1.0 constant:200];            [grayView addConstraint:widthConstraint];    [grayView addConstraint:heightConstraint];    [self.view addConstraint:leftConstraint];    [self.view addConstraint:topConstraint];


方法二:VFL(Visual Format Language)

    UIView *grayView = [UIView new];    grayView.backgroundColor = [UIColor lightGrayColor];    grayView.translatesAutoresizingMaskIntoConstraints = NO;    [self.view addSubview:grayView];    // format参数    NSString *Hvfl = @"H:|-left-[grayView(150)]";    NSString *Vvfl = @"V:|-top-[grayView(100)]";    // 设置 margin 数值    NSDictionary *metrics = @{@"top":@200,@"left":@100};    // 把要添加约束的view 转成字典    NSDictionary *views = NSDictionaryOfVariableBindings(grayView);// 这个方法会自动把传入的参数椅子垫的形式返回,字典的key就是其本身的名字,如@{@"grayView":grayView}    // 添加对齐方式    NSLayoutFormatOptions ops = NSLayoutFormatAlignAllLeft | NSLayoutFormatAlignAllTop;// 左边与顶部        NSArray *Hconstraints = [NSLayoutConstraint constraintsWithVisualFormat:Hvfl options:ops metrics:metrics views:views];    NSArray *Vconstraints = [NSLayoutConstraint constraintsWithVisualFormat:Vvfl options:ops metrics:metrics views:views];    [self.view addConstraints:Hconstraints];    [self.view addConstraints:Vconstraints];


运行如下:




本篇博客只是针对基础知识点的整理归纳与简单应用 详细代码解析请参考如下博客:

史上比较用心的纯代码实现 AutoLayout

iOS Autolayout之VFL




原创粉丝点击