问题:如何实现图中的view,要求能根据文本的长度自适应。(消息有多少条不一定,所以宽度肯定不固定)
首先来分解一下:
A:View —— 外层容器,红色背景、圆角
B:ImageView —— 圆角ImageView,用于显示头像
C:Label —— 白色字体
D:ImageView —— 右侧箭头
其中大小固定的是B和D,C会根据具体消息有多少条,发生宽度的改变,A会随着BCD总宽度的改变而改变。
解决办法:
使用AutoLayout,这里用了Masonry,上代码,重要的都在代码中注释了,核心思想是:不要设定A的宽度,并让C来将A撑起来(因为UILabel有这个特性)。
UIView *contentView = [UIView new];
contentView.backgroundColor = [HMStyle themeMainColor];
contentView.layer.cornerRadius = 20.0f;
[self addSubview:contentView];
[contentView mas_makeConstraints:^(MASConstraintMaker *make) { // 不设置宽度,让内容将他撑起来
make.height.equalTo(@(contentHeight));
make.centerX.equalTo(self);
make.bottom.equalTo(self);
}];
self.m_MessageImageView = [UIImageView new];
self.m_MessageImageView.image = [UIImage imageNamed:@"user_normal_avatar"];
self.m_MessageImageView.layer.cornerRadius = 15.0f;
self.m_MessageImageView.layer.masksToBounds = YES;
self.m_MessageImageView.layer.borderColor = [UIColor whiteColor].CGColor;
self.m_MessageImageView.layer.borderWidth = 2.0f;
[contentView addSubview:self.m_MessageImageView];
[self.m_MessageImageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.width.height.equalTo(@30);
make.left.equalTo(contentView.mas_left).offset(5);
make.centerY.equalTo(contentView);
}];
// 用label左右延伸将父组件撑起来
self.m_MessageLabel = [UILabel new];
self.m_MessageLabel.textAlignment = NSTextAlignmentLeft;
self.m_MessageLabel.textColor = [UIColor whiteColor];
self.m_MessageLabel.font = [UIFont systemFontOfSize:14.0f];
self.m_MessageLabel.text = @"小家有--条新消息";
[contentView addSubview:self.m_MessageLabel];
[self.m_MessageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(contentView.mas_left).offset(40); // 加上头像和margin的大小
make.top.bottom.equalTo(contentView);
make.right.equalTo(contentView.mas_right).offset(-20); // 加上箭头和margin的大小
}];
UIImageView *imageView = [UIImageView new];
imageView.image = [UIImage imageNamed:@"7x13_arrow"];
[contentView addSubview:imageView];
[imageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(contentView.mas_right).offset(-10);
make.width.equalTo(@7);
make.height.equalTo(@13);
make.centerY.equalTo(contentView.mas_centerY);
}];