基礎(chǔ)
- 官方WWDC的基礎(chǔ)教學(xué)視頻:202 – Introduction to Auto Layout for iOS and OS X https://developer.apple.com/videos/wwdc/2012/?id=202,228 – Best Practices for Mastering Auto Layout https://developer.apple.com/videos/wwdc/2012/?id=228,232 – Auto Layout by Example https://developer.apple.com/videos/wwdc/2012/?id=232
- 約束條件是用的可視格式語(yǔ)言庇绽,官方文檔:https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/VisualFormatLanguage/VisualFormatLanguage.html
原理
視圖顯示前會(huì)有兩個(gè)步驟,順序是updating constraints -> laying out views -> 顯示婴噩。
- Updating constraints:從子視圖到父視圖,布局會(huì)在實(shí)際設(shè)置frame時(shí)使用,調(diào)用setNeedsUpdateConstraints觸發(fā)操作脓恕。自定義視圖的話可以重寫(xiě)updateConstraints增加本地約束驯杜。
- Laying out views:布局視圖是從父視圖到子視圖受啥,通過(guò)setNeedsLayout觸發(fā)。調(diào)用layoutIfNeeded可以強(qiáng)制系統(tǒng)立刻更新視圖布局鸽心。
自定義視圖自動(dòng)布局的過(guò)程
Instrinsic Content Size
實(shí)現(xiàn)Instrinsic Content Size需要重寫(xiě)intrinsicContentSize返回合適的大小滚局,有會(huì)影響尺寸改變的時(shí)候調(diào)用invalidateInstrinsicContentSize。一個(gè)方向設(shè)置Instrinsic Content Size顽频,另一個(gè)方向尺寸返回UIViewNoIntrinsicMetric
Compression Resistance 和 Content Hugging
定義了Instrinsic Content Size 才能夠在視圖兩個(gè)方向上分配 Compression Resistance 和 Content Hugging 藤肢。比如一個(gè)Instrinsic Content Size為{100,30}的label,Compression Resistance為750糯景,Content Hugging為250嘁圈,約束條件可視格式語(yǔ)言如下
H:[label(<=100@250)]
H:[label(>=100@750)]
V:[label(<=30@250)]
V:[label(>=30@750)]
Frame和Alignment Rect
如果需要可以重寫(xiě)alignmentRectForFrame:和frameForAlignmentRect:,Instrinsic Content Size尺寸引用它的alignment rect而不是frame
Baseline Alignment
通過(guò)viewForBaselineLayout來(lái)激活基線對(duì)齊蟀淮。
控制布局
- 本地約束:添加本地約束的地方是updateConstraints最住。增加布局子視圖約束條件后調(diào)用[super updateConstraints]。
- 控制子視圖布局:如果不能利用布局約束條件達(dá)到子視圖預(yù)期布局可以重寫(xiě)layoutSubviews怠惶∥卵В可以參看WWDC視頻的一個(gè)例子WWDC session 228 – Best Practices for Mastering Auto Layout http://onevcat.com/2012/09/autoayout/
- layoutSubviews
{
[super layoutSubviews];
if (self.subviews[0].frame.size.width <= MINIMUM_WIDTH)
{
[self removeSubviewConstraints];
self.layoutRows += 1; [super layoutSubviews];
}
}
- updateConstraints
{
// 根據(jù) self.layoutRows 添加約束...
[super updateConstraints];
}
對(duì)于不固定高度的多行文本處理
比如說(shuō)UILabel和NSTextField文本的高度取決于行的寬度,這兩個(gè)類有個(gè)perferredMaxLayoutWidth的屬性甚疟,可以指定行寬度的最大值仗岖,以便計(jì)算固有內(nèi)容尺寸。
- (void)layoutSubviews
{
//第一次調(diào)用獲得label的frame
[super layoutSubviews];
myLabel.preferredMaxLayoutWidth = myLabel.frame.size.width;
//第二次調(diào)用為了改變后更新布局
[super layoutSubviews];
}
//也可以在label子類本身這樣做
@implementation MyLabel
- (void)layoutSubviews
{
self.preferredMaxLayoutWidth = self.frame.size.width;
[super layoutSubviews];
}
@end
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
myLabel.preferredMaxLayoutWidth = myLabel.frame.size.width;
[self.view layoutIfNeeded];
}
動(dòng)畫(huà)
- 使用Core Animation方法
//非Auto Layout的寫(xiě)法
[UIView animateWithDuration:1 animations:^{
myView.frame = newFrame;
}];
// 更新約束览妖,Auto Layout的寫(xiě)法轧拄,主要不要更改view的frame,因?yàn)関iew使用了Auto Layout后frame的設(shè)置任務(wù)已經(jīng)由布局系統(tǒng)代勞了讽膏。
[UIView animateWithDuration:1 animations:^{
[myView layoutIfNeeded];
}];
- 使用transform來(lái)產(chǎn)生動(dòng)畫(huà)檩电,將這個(gè)view嵌入到一個(gè)view的容器內(nèi),然后在這個(gè)容器內(nèi)重寫(xiě)layoutSubviews
- (void)layoutSubviews
{
[super layoutSubviews];
static CGPoint center = {0,0};
if (CGPointEqualToPoint(center, CGPointZero)) {
// 在初次布局后獲取中心點(diǎn)
center = self.animatedView.center;
} else {
// 將中心點(diǎn)賦回給動(dòng)畫(huà)視圖
self.animatedView.center = center;
}
}
調(diào)試
不可滿足的約束條件
遇到不可滿足的約束條件只能在輸入的日志中看到視圖的內(nèi)存地址府树。
(lldb) po 0x7731880
$0 = 124983424 <UIView: 0x7731880; frame = (90 -50; 80 100);
layer = <CALayer: 0x7731450>>
(lldb) po [0x7731880 superview]
$2 = 0x07730fe0 <UIView: 0x7730fe0; frame = (32 128; 259 604);
layer = <CALayer: 0x7731150>>
(lldb) po [[0x7731880 superview] recursiveDescription]
$3 = 0x07117ac0 <UIView: 0x7730fe0; frame = (32 128; 259 604); layer = <CALayer: 0x7731150>>
| <UIView: 0x7731880; frame = (90 -50; 80 100); layer = <CALayer: 0x7731450>>
| <UIView: 0x7731aa0; frame = (90 101; 80 100); layer = <CALayer: 0x7731c60>>
可以在控制臺(tái)修改有問(wèn)題的視圖
(lldb) expr ((UIView *)0x7731880).backgroundColor = [UIColor purpleColor]
這里有Danielhttps://twitter.com/danielboedewadt的一個(gè)調(diào)試Auto Layout的范例:https://github.com/objcio/issue-3-auto-layout-debugging
有歧義的布局
UIView提供三種方法:hasAmbiguousLayout俐末,exerciseAmbiguityInLayout和_autolayoutTrace(私有方法,正式產(chǎn)品里不要包含)奄侠。如果有歧義那么hasAmbiguousLayout返回YES卓箫。
@implementation UIView (AutoLayoutDebugging)
- (void)printAutoLayoutTrace {
#ifdef DEBUG
NSLog(@"%@", [self performSelector:@selector(_autolayoutTrace)]);
#endif
}
@end
_autolayoutTrace打印如下:
2013-07-23 17:36:08.920 FlexibleLayout[4237:907]
*<UIWindow:0x7269010>
| *<UILayoutContainerView:0x7381250>
| | *<UITransitionView:0x737c4d0>
| | | *<UIViewControllerWrapperView:0x7271e20>
| | | | *<UIView:0x7267c70>
| | | | | *<UIView:0x7270420> - AMBIGUOUS LAYOUT
| | <UITabBar:0x726d440>
| | | <_UITabBarBackgroundView:0x7272530>
| | | <UITabBarButton:0x726e880>
| | | | <UITabBarSwappableImageView:0x7270da0>
| | | | <UITabBarButtonLabel:0x726dcb0>
使用exerciseAmbiguityInLayout
@implementation UIView (AutoLayoutDebugging)
- (void)exerciseAmiguityInLayoutRepeatedly:(BOOL)recursive {
#ifdef DEBUG
if (self.hasAmbiguousLayout) {
[NSTimer scheduledTimerWithTimeInterval:.5
target:self
selector:@selector(exerciseAmbiguityInLayout)
userInfo:nil
repeats:YES];
}
if (recursive) {
for (UIView *subview in self.subviews) {
[subview exerciseAmbiguityInLayoutRepeatedly:YES];
}
}
#endif
} @end
約束條件代碼
- 可視化結(jié)構(gòu)語(yǔ)言 (visual format language, VFL)官方文檔:http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/instm/UIView/translatesAutoresizingMaskIntoConstraints
- 如果是使用代碼設(shè)置約束,需要將 translatesAutoResizingMaskIntoConstraints 設(shè)置為NO垄潮。
- constraintsWithVisualFormat:options:metrics:views:方法的option參數(shù)可以允許調(diào)整一定范圍內(nèi)的view烹卒,不同于格式化字符只能影響一個(gè)view闷盔。比如使用NSLayoutFormatAlignAllTop排列可視化語(yǔ)言里所有view為上邊緣對(duì)其。
- 父視圖中居中子視圖的技巧旅急,利用了不均等約束和可選參數(shù)逢勾。下面代碼在父視圖中水平排列了一個(gè)視圖
UIView *superview = theSuperView;
NSDictionary *views = NSDictionaryOfVariableBindings(superview, subview);
NSArray *c = [NSLayoutConstraint
constraintsWithVisualFormat:@"V:[superview]-(<=1)-[subview]"]
options:NSLayoutFormatAlignAllCenterX
metrics:nil
views:views];
[superview addConstraints:c];
- 垂直的排列一系列view,想要它們垂直方向間距一致藐吮,水平方向上所有view以他們的左邊緣對(duì)齊
@implementation UIView (AutoLayoutHelpers)
+ leftAlignAndVerticallySpaceOutViews:(NSArray *)views
distance:(CGFloat)distance
{
for (NSUInteger i = 1; i < views.count; i++) {
UIView *firstView = views[i - 1];
UIView *secondView = views[i];
firstView.translatesAutoResizingMaskIntoConstraints = NO;
secondView.translatesAutoResizingMaskIntoConstraints = NO;
NSLayoutConstraint *c1 = constraintWithItem:firstView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:secondView
attribute:NSLayoutAttributeTop
multiplier:1
constant:distance];
NSLayoutConstraint *c2 = constraintWithItem:firstView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:secondView
attribute:NSLayoutAttributeLeading
multiplier:1
constant:0];
[firstView.superview addConstraints:@[c1, c2]];
}
}
@end