Auto Layout学习

基础

原理

视图显示前会有两个步骤,顺序是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。可以参看WWDC视频的一个例子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

约束条件代码

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容