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那套东西,体积小,写起来更底层同时也不乏可读性。html

 

好比上文中的简单的两个黄色方块的程序,用PureLayout写更快捷。ios

 

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

 

而后加一个建立View的辅助函数:github

 

 

- (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就能够了,代码很是好理解:app

 

 

//建立两个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];

 

 

 

 

运行结果和上文同样:函数

 

屏幕快照 2013-11-05 下午5.58.45

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



文/Ray_win(简书做者) 原文连接:http://www.jianshu.com/p/2bebe9ef24fd 著做权归做者全部,转载请联系做者得到受权,并标注“简书做者”。
本站公众号
   欢迎关注本站公众号,获取更多信息