实现具有 intrinsic content size 功能的自定义视图类(支持 xib/sb 使用)

271 篇文章 0 订阅
11 篇文章 0 订阅

对于 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。

  • 首先,创建继承自 UIView 的视图类 SmartLabel,为了简化,只支持设置 title(字体、颜色、高度暂时写死)

    @interface SmartLabel : UIView
    
    @property (nonatomic, copy) NSString *title;
    
    @end
  • 接着,来看下 .m 中的实现

    @interface SmartLabel ()
    
    @property (nonatomic, strong) UILabel *titleLabel;
    @property (nonatomic, strong) UILabel *tipLabel;
    
    @end
    
    @implementation SmartLabel
    
    - (instancetype)initWithCoder:(NSCoder *)aDecoder {
        if (self = [super initWithCoder:aDecoder]) {
            [self commonInit];
        }
    
        return self;
    }
    
    - (instancetype)initWithFrame:(CGRect)frame {
        if (self = [super initWithFrame:frame]) {
            [self commonInit];
        }
    
        return self;
    }
    
    - (void)commonInit {
        self.backgroundColor = [UIColor redColor];
    
        UILabel *titleLabel = [UILabel new];
        titleLabel.font = [self labelsFont];
        titleLabel.textColor = [UIColor greenColor];
        titleLabel.text = @"";
        self.titleLabel = titleLabel;
        [self addSubview:self.titleLabel];
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.top.trailing.equalTo(self);
            make.height.equalTo(@25);
        }];
        [self.titleLabel setContentCompressionResistancePriority:1 forAxis:UILayoutConstraintAxisHorizontal];
    
        UILabel *tipLabel = [UILabel new];
        tipLabel.font = [self labelsFont];
        tipLabel.textColor = [UIColor blueColor];
        tipLabel.text = @"";
        self.tipLabel = tipLabel;
        [self addSubview:self.tipLabel];
        [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.leading.trailing.bottom.equalTo(self);
                make.top.equalTo(self.titleLabel.mas_bottom);
        }];
        [self.tipLabel setContentCompressionResistancePriority:0 forAxis:UILayoutConstraintAxisHorizontal];
    }
    
    - (void)layoutSubviews {
        [super layoutSubviews];
    
        self.tipLabel.text = [NSString stringWithFormat:@"width: %.0f", self.size.width];
    }
    
    - (void)setTitle:(NSString *)title {
        _title = [title copy];
    
        self.titleLabel.text = _title;
    
        [self invalidateIntrinsicContentSize];
    }
    
    - (CGSize)intrinsicContentSize {
        CGFloat titleLabelWidth = [_title textSizeForOneLineWithFont:[self labelsFont]].width;
    
        return CGSizeMake(titleLabelWidth, 50);
    }
    
    - (UIFont *)labelsFont {
        static UIFont *s_labelsFont = nil;
    
        if (!s_labelsFont) {
            s_labelsFont = [UIFont systemFontOfSize:12.f];
        }
    
        return s_labelsFont;
    }
    
    @end

    其中重写 initWithCoder: 是为了支持 xib/storyboard 中使用
    添加一个 tipLabel 方便查看当前视图的宽度(方便测试效果而已)
    其中 titleLabel 和 tipLabel 本身也有 intrinsic content size 生成的隐式约束约束,为了不影响自定义视图水平方向上的隐式约束,将其水平方向的 content compression resistance 优先级设置为 0。
    其中字体、颜色、高度各种写死,只是为了简化,自己实现自定义视图时最好根据需要可配置。
    当一些可能影响 intrinsic content size 的属性发生变化,需要调用 [self invalidateIntrinsicContentSize]; 触发重新根据 -(CGSize)intrinsicContentSize; 设置隐式约束。

  • 最后,我们来测试一下这个视图在 xib 中的使用
    这里写图片描述


    这里写图片描述

    注意图中标注的 6 个地方,由于系统控件可以直接使用 Intrinsic Size - Default (System Defined),但是自定义视图需要选择 Placeholder,里面的宽高可以先随便设置,正如其名字所属,只是先保证 xib/storyboard 中的相对布局不报错,具体可以看下 IB 中说明如下图。
    这里写图片描述

接着看下测试代码:

@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

再来看下运行后的效果:
这里写图片描述

再修改一下两者的水平方向上的 content compression resistance 优先级,看下运行效果:
这里写图片描述


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

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值