知识点

Auto Layout学习

2015-09-06  本文已影响505人  星光社的戴铭

基础

原理

视图显示前会有两个步骤,顺序是updating constraints -> laying out views -> 显示。

自定义视图自动布局的过程

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来激活基线对齐。

控制布局

- 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];
}

动画

//非Auto Layout的写法
[UIView animateWithDuration:1 animations:^{
     myView.frame = newFrame;
}];
// 更新约束,Auto Layout的写法,主要不要更改view的frame,因为view使用了Auto Layout后frame的设置任务已经由布局系统代劳了。
[UIView animateWithDuration:1 animations:^{
     [myView layoutIfNeeded];
}];
- (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];
@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
上一篇 下一篇

猜你喜欢

热点阅读