在上一篇 AutoLayout 簡介中,我們透過 Interface Builder 自動建立了 constraint,而 constraint 就是 autolay out 的基礎。其實 constraint 也是可以手動建立的。
如果我們不是用 IB 而是用程式化的方式建立之簡介中的案例,我們可以寫一段程式在 ViewController 的 loadview 中,如下:
UIView *superView=self.view;
UIButton *theButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
UIButton *anotherButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[theButton setTranslatesAutoresizingMaskIntoConstraints:NO];
[anotherButton setTranslatesAutoresizingMaskIntoConstraints:NO];
[theButton setTitle:@"Hello" forState:UIControlStateNormal];
[anotherButton setTitle:@"Good" forState:UIControlStateNormal];
self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]];
[superView addSubview:theButton];
[superView addSubview:anotherButton];
NSLayoutConstraint *cn= [NSLayoutConstraint constraintWithItem:theButton
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:superView
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0.0
];
[superView addConstraint:cn];
cn= [NSLayoutConstraint constraintWithItem:theButton
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:superView
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:-20.0
];
[superView addConstraint:cn];
cn=
[NSLayoutConstraintconstraintWithItem:anotherButton
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:theButton
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:0];
[superView addConstraint:cn];
cn=
[NSLayoutConstraint constraintWithItem:anotherButton
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:theButton
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:-10];
[superView addConstraint:cn];
在這段程式的前半段,我們在 self.view 中,加入了兩個 button,【theButton】和【anotherButton】,這段程式所有學過一點 iOS 開發的人都不難理解,但我們在後半段,在 self.view 中,加入了四個 NSLayoutConstraint Object。它就可以用來對齊物件了。
先來看一下第一個 NSLayoutConstraint
NSLayoutConstraint *cn=
[NSLayoutConstraint constraintWithItem:theButton
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:superView
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0.0
];
[superView addConstraint:cn];
如果用中文說明這段程式的意義就是:theButton 的中央X軸座標對齊上層 X 軸座標,分行說明如下
constraintWithItem:theButton
// theButton 這個 Object
attribute:NSLayoutAttributeCenterX
// 它的屬性:中央 X 軸座標
relatedBy:NSLayoutRelationEqual
// 建立一個等於依存關係
toItem:superView
// 與它的上層 View 的
attribute:NSLayoutAttributeCenterX
// 中央 X 軸座標
multiplier:1.0
// 比例,基本不太會用到,設1就可以了
constant:0.0
// 偏移值,本例為 0 完全對齊可以是 ﹣10 向左十點或 10 向右十點等
同樣的,另外三可以依此推測它的意義,就可得知共有四個條件
theButton 的中央X軸座標對齊上層 X 軸座標
anotherButton 的左側對齊 theButton 的左側
theButton 的下面對齊 self.view 的 下面並高10點
anotherButton 的下面對齊 theButton 的上面並高十點
所以顯示的畫面就會像這樣:
或者是這樣:
留言列表