实现具有 intrinsic content size 功能的自

2018-01-01  本文已影响0人  BenXia

对于 intrinsic content size 不熟悉的童鞋,建议先看一下下面这篇文章,再开始本文的阅读

只有 20% 的 iOS 程序员能看懂:详解 intrinsicContentSize 及 约束优先级/content Hugging/content Compression Resistance

iOS 开发中经常需要使用 xib/storyboard 配合 AutoLayout 来做一些界面的布局适配工作,其中 UILabel、UIButton、UIImageView 等系统控件,在使用相对布局时候只指定位置不指定大小也可以正常工作,原因就是其借助 intrinsic content size 功能加了几条隐式的约束,辅助确定其大小。

那么我们不禁发问,我们自定义的视图类能否也能做到像这几个系统控件一样,在使用 xib/storyboard 时简化我们设置布局,特别是简化对于“出现多个视图放不下需要考虑优先压缩那个视图”的处理,只需要通过控制 content compression resistance 优先级就可以呢?

答案是肯定的,下面介绍具体怎么操作。


现在假设系统没有 UILabel,我自己实现一个具有 Intrinsic Content Size 功能的自定义视图,命名为 SmartLabel。

接着看下测试代码:

@interface SmartLabelTestVC ()

@property (weak, nonatomic) IBOutlet SmartLabel *smartView;

@property (nonatomic, strong) NSTimer *repeatTimer;

@end

@implementation SmartLabelTestVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    self.view.backgroundColor = [UIColor whiteColor];

    if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }

    @weakify(self);
    self.repeatTimer = [NSTimer scheduledTimerWithTimeInterval:0.3 repeats:YES block:^(NSTimer *timer) {
        @strongify(self);
        [self appendTextToSmartView];
        if (self.smartView.title.length >= 60) {
            [timer invalidate];
            timer = nil;
        }
    }];
    [[NSRunLoop mainRunLoop] addTimer:self.repeatTimer forMode:NSRunLoopCommonModes];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)appendTextToSmartView {
    static int s_num = 0;

    s_num++;
    if (s_num >= 10) {
        s_num = 0;
    }

    self.smartView.title = [NSString stringWithFormat:@"%@%d", self.smartView.title ? : @"", s_num];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    NSLog (@"%@ dealloc", [self class]);
}

@end

再来看下运行后的效果:


运行效果gif

再修改一下两者的水平方向上的 content compression resistance 优先级,看下运行效果:


运行效果gif

总结下来,自定义视图支持 intrinsic content size 后也可以像系统控件一样在 xib/storyboard 中简化约束的设置,通过控制 content hugging/content compression resistance 的优先级就可以很方便的控制特殊场景下的视图布局。这样可以将原本需要写在 ViewController 中的繁杂适配逻辑解耦到各个 View 内部,避免了每个使用到的 ViewController 中都要写繁杂的适配逻辑,所以没有使用的小伙伴可以考虑大刀耍起来了,珍爱生命,点滴做起~

代码地址:https://github.com/BenXia/AutoLayoutDemo

上一篇 下一篇

猜你喜欢

热点阅读