需求是这样的,我需要在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;
}
结果如下