以前寫過兩篇文章: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];
運行結果和上文同樣:函數
原文地址:http://www.mgenware.com/blog/?p=2335code