iOS自定义表格视图单元格标签调整大小损坏

llo*_*kes 1 iphone objective-c uikit uilabel ios

我正在为客户编写一个iOS应用程序,主视图是一个表视图,我用文本填充单元格,就像大多数iOS twitter客户端一样.

我创建了一个带有3个标签的自定义单元格视图,并使用文本填充这些标签.其中一个标签需要根据文本的数量自动调整大小(最多140个字符).

这工作正常,直到我向上/向下滚动列表,当文本延伸到一个完整的行(如标签已扩展)或只占用部分空间,因此它更深入,溢出到其他标签(我确实有根据另一个类似的SO问题启用"剪辑子视图"

因此,当首次加载表及其数据时,屏幕如下所示:

滚动之前http://lloydsparkes.co.uk/files/iOS-BeforeScrolling.png

经过一些滚动后,它看起来像:

滚动后http://lloydsparkes.co.uk/files/iOS-AfterScrolling.png

所以看起来标签在滚动过程中正在调整大小(可能是由于同一个单元被重用了?)而没有调整大小到正确的大小.

我填写单元格的代码是:

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString *myID = @"customCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:myID];

if(cell == NULL) {

    [[NSBundle mainBundle] loadNibNamed:@"CustomCellView" owner:self options:nil];

    cell = customCell;
    self.customCell = nil;
}

Post *p = [posts objectAtIndex:indexPath.row];

UILabel *label = (UILabel*)[cell viewWithTag:15];
label.text = p.Name;

label = (UILabel*)[cell viewWithTag:10];
label.text = p.Text;
[label sizeToFit];

label = (UILabel*)[cell viewWithTag:20];
label.text = [p Source];

//[cell layoutSubviews];

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

所以我要问的是,是什么导致了这个问题?它怎么解决?

Fel*_*ino 7

sizeToFit方法可能以奇怪的方式运行,因为每次cellForRowAtIndexPath调用UILabel帧都会更改.

您可以尝试的一件事是label在调用之前将对象的框架设置回原始大小(在NIB文件中设置的valeu)sizeToFit

[label setFrame:CGRectMake(0.0f, 0.0f, 100.0f, 50.0f)];    
[label sizeToFit];
Run Code Online (Sandbox Code Playgroud)