初始化TableViewCell时获取到的宽度错误
来源:互联网 发布:精通qt4编程 源码 编辑:程序博客网 时间:2024/05/18 02:43
需求是这样的,我需要在TableViewCell里面加入一个和Cell的宽高一样大的Label,我使用_contentLabel = [[UILabel alloc] initWithFrame:self.contentView.bounds];
来设置Label的宽高,然后使用懒加载在初始化方面里面添加label,完整的代码如下:
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{ self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { [self.contentView addSubview:self.contentLabel]; } return self;}- (UILabel *)contentLabel{ if (!_contentLabel) { _contentLabel = [[UILabel alloc] initWithFrame:self.contentView.bounds]; _contentLabel.textAlignment = NSTextAlignmentCenter; _contentLabel.font = [UIFont systemFontOfSize:12]; _contentLabel.backgroundColor = [UIColor redColor]; } return _contentLabel;}
Label总是占不满屏幕。我在iPhone5上面运行正常,在iPhone 6上面运行出错了,断点调试后才发现宽度是320,高度是44,结果如下:
查了一资料,可能是历史遗留问题,所以tableViewCell在初始化的时候宽高默认是320*44.只有在布局的时候才会调整到设置的高度。所以可以重写layoutSubviews方法。在layoutSubviews里面加载label即可。
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{ self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { } return self;}- (void)layoutSubviews{ [super layoutSubviews]; [self.contentView addSubview:self.contentLabel];}- (UILabel *)contentLabel{ if (!_contentLabel) { _contentLabel = [[UILabel alloc] initWithFrame:self.contentView.bounds]; _contentLabel.textAlignment = NSTextAlignmentCenter; _contentLabel.font = [UIFont systemFontOfSize:12]; _contentLabel.backgroundColor = [UIColor redColor]; } return _contentLabel;}
结果如下
0 0
- 初始化TableViewCell时获取到的宽度错误
- 初始化TableViewCell时获取到的宽度错误
- TableViewCell的初始化
- iphone 控制tableviewcell的宽度
- 获取选中TableViewCell的index
- 获取tableViewcell副标题的方法
- 三种初始化加载tableViewCell的方法
- 控制tableviewcell的imageView宽度一致的代码
- xib定义的tableviewcell宽度固定,无法适配屏幕
- $(window).width()获取宽度错误
- css获取到指定元素的宽度,在回调返回宽度值
- 获取tableViewCell点击的位置和indexPath
- 通过button获取所在的tableViewCell
- AVAudioPlayer获取网络语音时,把下载的data写到本地,在初始化player
- js获取table中的td宽度并赋值到另一个table的td中,实现宽度对齐
- [错误记录]tableviewcell问题
- 初始化JTable 各列的宽度
- (方案)正确初始化view的宽度
- [leetcode]41. First Missing Positive,C++/python实现,hard难度
- Hbase介绍
- c primer plus第8章总结:字符输入输出
- n个元素的全排列(非递归+去重)
- SystemClock 中方法的意义
- 初始化TableViewCell时获取到的宽度错误
- Centos下Yum安装PHP5.5,5.6,7.0
- RecyclerView中item无法充满的问题
- O2O(Online To Offline)
- MAC查看端口占用情况
- QuickTest Professional(QTP): 连接Oracle数据库
- Neural Networks and Deep Learning 学习笔记(三)
- cmake使用笔记
- Timer和handler的使用