美文网首页知识点
Auto Layout学习

Auto Layout学习

作者: 星光社的戴铭 | 来源:发表于2015-09-06 17:47 被阅读505次

基础

原理

视图显示前会有两个步骤,顺序是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

相关文章

网友评论

    本文标题:Auto Layout学习

    本文链接:https://www.haomeiwen.com/subject/vrmdcttx.html