iOS-初始化TableViewCell時獲取到的寬度錯誤
阿新 • • 發佈:2021-01-13
需求是這樣的,我需要在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; }
結果如下