首次出现时无法在UITableViewCell中更改UILabel的帧(使用Autolayout)

the*_*ncs 7 objective-c uitableview ios layoutsubviews autolayout

我里面有一个原型单元,里面UITableView有一个UILabel.我想根据标签中文本的大小动态更改标签(和单元格)的大小.

cellForRowAtIndexPath像这样创建原型单元格:

static NSString *CellIdentifier = @"ProgramDetailCell";
ProgramDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.descriptionLabel.text = self.program.subtitle;
return cell;
Run Code Online (Sandbox Code Playgroud)

然后我ProgramDetailCell有以下实现:

@implementation ProgramDetailCell
- (void)layoutSubviews {
    [super layoutSubviews];
    [self.descriptionLabel sizeToFit];
}
@end
Run Code Online (Sandbox Code Playgroud)

第一次显示单元格时,layoutSubviews会调用,但descriptionLabel不会调整大小.但是,如果我向下滚动表并再次备份,则会显示"重复使用"单元格,并正确调整标签大小!

为什么第一次显示单元格时它不起作用 - 我需要做些什么来修复它.

提前致谢!

Yll*_*low 9

在xib中,转到第一个选项卡,在Interface Builder Document下,取消选中"使用自动布局"框.


sun*_*ppy 1

因为何时layoutSubviews调用您的descriptionLabel文本尚未设置。当您滚动时,文本就会被设置。所以现在是正确的。

我建议您sizeToFit在设置文本后致电。

static NSString *CellIdentifier = @"ProgramDetailCell";
ProgramDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.descriptionLabel.text = self.program.subtitle;
[cell.descriptionLabel sizeToFit];
return cell;
Run Code Online (Sandbox Code Playgroud)