UILabel SizeToFit的UITableView在滚动时会变得混乱

Dek*_*man 7 objective-c uitableview uilabel ios sizetofit

大家好我对我有问题tableview,我制作Cell with uilabelwith SizeToFit然后计算UILabel高度设置单元格高度一切正常,除非我滚动我tableView的文本变得奇怪,如每行一个字符:

我的TableViewVell方法是:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}


UILabel *label = (UILabel *)[cell viewWithTag:1];
label.text = [someArray objectAtIndex:indexPath.row];
// Set the UILabel to fit my text;
messageLabel.lineBreakMode = UILineBreakModeWordWrap;
messageLabel.numberOfLines = 0;
[messageLabel sizeToFit];


return cell;   
}
Run Code Online (Sandbox Code Playgroud)

Cell Height保持正确的大小问题只有UILabel...这是我加载视图时的结果:

第一个截图

这是在我开始滚动TableView之后:

第二个截图

任何帮助???

Val*_*hie 20

该方法sizeToFit尊重框架的宽度并调整height.并且表视图单元重用单元.将这两种行为结合起来可能会导致您所描述的问题.

您的标签之一(内容非常短)(例如,在第4个单元格中标有"jio"),会调整其大小,sizeToFit并且生成的宽度小于您想要的原始宽度.

之后,表视图重用单元格,sizeToFit仍然遵循从先前调用计算的小宽度sizeToFit.

解决方案:

1)每次拨打电话前,请将框架的宽度设置为原始的标签宽度sizeToFit:

CGRect frame = messageLabel.frame;
frame.size.width = 100.0; //you need to adjust this value 
messageLabel.frame = frame;
Run Code Online (Sandbox Code Playgroud)

2)使用行高计算并改为设置框架高度.无需使用sizeToFit.


小智 1

你可能应该对你的单元进行子类化并清理 UILabel

 override func prepareForReuse() {
    super.prepareForReuse()
    self.label.text = nil
}
Run Code Online (Sandbox Code Playgroud)