基礎
- 官方WWDC的基礎教學視頻: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
- 約束條件是用的可視格式語言,官方文檔:https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/VisualFormatLanguage/VisualFormatLanguage.html
原理
視圖顯示前會有兩個步驟,順序是updating constraints -> laying out views -> 顯示。
- Updating constraints:從子視圖到父視圖,布局會在實際設置frame時使用,調用setNeedsUpdateConstraints觸發操作。自定義視圖的話可以重寫updateConstraints增加本地約束。
- Laying out views:布局視圖是從父視圖到子視圖,通過setNeedsLayout觸發。調用layoutIfNeeded可以強制系統立刻更新視圖布局。
自定義視圖自動布局的過程
Instrinsic Content Size
實現Instrinsic Content Size需要重寫intrinsicContentSize返回合適的大小,有會影響尺寸改變的時候調用invalidateInstrinsicContentSize。一個方向設置Instrinsic Content Size,另一個方向尺寸返回UIViewNoIntrinsicMetric
Compression Resistance 和 Content Hugging
定義了Instrinsic Content Size 才能夠在視圖兩個方向上分配 Compression Resistance 和 Content Hugging 。比如一個Instrinsic Content Size為{100,30}的label,Compression Resistance為750,Content Hugging為250,約束條件可視格式語言如下
H:[label(<=100@250)]
H:[label(>=100@750)]
V:[label(<=30@250)]
V:[label(>=30@750)]
Frame和Alignment Rect
如果需要可以重寫alignmentRectForFrame:和frameForAlignmentRect:,Instrinsic Content Size尺寸引用它的alignment rect而不是frame
Baseline Alignment
通過viewForBaselineLayout來激活基線對齊。
控制布局
- 本地約束:添加本地約束的地方是updateConstraints。增加布局子視圖約束條件后調用[super updateConstraints]。
- 控制子視圖布局:如果不能利用布局約束條件達到子視圖預期布局可以重寫layoutSubviews??梢詤⒖碬WDC視頻的一個例子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
{
// 根據 self.layoutRows 添加約束...
[super updateConstraints];
}
對于不固定高度的多行文本處理
比如說UILabel和NSTextField文本的高度取決于行的寬度,這兩個類有個perferredMaxLayoutWidth的屬性,可以指定行寬度的最大值,以便計算固有內容尺寸。
- (void)layoutSubviews
{
//第一次調用獲得label的frame
[super layoutSubviews];
myLabel.preferredMaxLayoutWidth = myLabel.frame.size.width;
//第二次調用為了改變后更新布局
[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];
}
動畫
- 使用Core Animation方法
//非Auto Layout的寫法
[UIView animateWithDuration:1 animations:^{
myView.frame = newFrame;
}];
// 更新約束,Auto Layout的寫法,主要不要更改view的frame,因為view使用了Auto Layout后frame的設置任務已經由布局系統代勞了。
[UIView animateWithDuration:1 animations:^{
[myView layoutIfNeeded];
}];
- 使用transform來產生動畫,將這個view嵌入到一個view的容器內,然后在這個容器內重寫layoutSubviews
- (void)layoutSubviews
{
[super layoutSubviews];
static CGPoint center = {0,0};
if (CGPointEqualToPoint(center, CGPointZero)) {
// 在初次布局后獲取中心點
center = self.animatedView.center;
} else {
// 將中心點賦回給動畫視圖
self.animatedView.center = center;
}
}
調試
不可滿足的約束條件
遇到不可滿足的約束條件只能在輸入的日志中看到視圖的內存地址。
(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>>
可以在控制臺修改有問題的視圖
(lldb) expr ((UIView *)0x7731880).backgroundColor = [UIColor purpleColor]
這里有Danielhttps://twitter.com/danielboedewadt的一個調試Auto Layout的范例:https://github.com/objcio/issue-3-auto-layout-debugging
有歧義的布局
UIView提供三種方法:hasAmbiguousLayout,exerciseAmbiguityInLayout和_autolayoutTrace(私有方法,正式產品里不要包含)。如果有歧義那么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
約束條件代碼
- 可視化結構語言 (visual format language, VFL)官方文檔:http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/instm/UIView/translatesAutoresizingMaskIntoConstraints
- 如果是使用代碼設置約束,需要將 translatesAutoResizingMaskIntoConstraints 設置為NO。
- constraintsWithVisualFormat:options:metrics:views:方法的option參數可以允許調整一定范圍內的view,不同于格式化字符只能影響一個view。比如使用NSLayoutFormatAlignAllTop排列可視化語言里所有view為上邊緣對其。
- 父視圖中居中子視圖的技巧,利用了不均等約束和可選參數。下面代碼在父視圖中水平排列了一個視圖
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以他們的左邊緣對齊
@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