陈斌彬的技术博客

Stay foolish,stay hungry

iOS-使用AutoLayout-PureLayout来简化操作

首先,把PureLayout源代码加入到工程中,或者用CocoaPods安装(podilfe中加pod ‘PureLayout')。

然后加一个创建View的辅助函数:

- (UIView*)createView {
    //有Autolayout不需要设置frame
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor yellowColor];
    //不允许AutoresizingMask转换成Autolayout, PureLayout内部也会帮你设置的。
    view.translatesAutoresizingMaskIntoConstraints = NO;

    return view;
}

在viewDidLoad中创建两个View,然后用PureLayout的方式加入Autolayout中的Constaint就可以了,代码非常好理解:

//创建两个View
UIView *view1 = [self createView];
UIView *view2 = [self createView];

//addSubview
[self.view addSubview:view1];
[self.view addSubview:view2];

//设置view1高度为70
[view1 autoSetDimension:ALDimensionHeight toSize:70.0];

//view1和view2都都距离父view边距为20
ALEdgeInsets defInsets = ALEdgeInsetsMake(20.0, 20.0, 20.0, 20.0);
[view1 autoPinEdgesToSuperviewEdgesWithInsets:defInsets excludingEdge:ALEdgeBottom];
[view2 autoPinEdgesToSuperviewEdgesWithInsets:defInsets excludingEdge:ALEdgeTop];

//两个view之间距离也是20
[view2 autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:view1 withOffset:defInsets.bottom];

运行结果

img