码迷,mamicode.com
首页 > 其他好文 > 详细

实现一个随着内容多少而拉伸的view

时间:2017-11-21 23:53:05      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:bounds   tom   4.0   code   UI   根据   tco   sub   col   

问题:如何实现图中的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);
}];

实现一个随着内容多少而拉伸的view

标签:bounds   tom   4.0   code   UI   根据   tco   sub   col   

原文地址:http://www.cnblogs.com/zhang-chi/p/7875383.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!