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

之前写过两篇文章:iOS: 在代码中使用Autolayout (1) – 按比例缩放和优先级和iOS: 在代码中使用Autolayout (2) – intrinsicContentSize和Content Hugging Priority讲述在iOS中使用代码来写Autolayout,读者可以看到,用代码写Autolayout是比较枯燥且容易出错的。当然也有很多代替方法,比如苹果官方的Visual Format Language,还有一些重量级的工程比如Masonry,这里介绍一个轻量的,支持iOS和OS X的工程PureLayout,之所以轻量是因为PureLayout没有再加入一套自己的语法,而是以Category的形式辅助苹果已有的NSLayoutConstraint那套东西,体积小,写起来更底层同时也不乏可读性。

比如上文中的简单的两个黄色方块的程序,用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];

 

运行结果和上文一样:

原文地址:http://www.mgenware.com/blog/?p=2335

你可能感兴趣的:(iOS--使用AutoLayout--PureLayout来简化操作)