初始化TableViewCell时获取到的宽度错误

需求是这样的,我需要在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,结果如下:
截图1
查了一资料,可能是历史遗留问题,所以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;

}

结果如下
截图2

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值