iOS 自定义表格视图单元格标签调整大小损坏 [英] iOS custom table view cell label resizing corruption

查看:61
本文介绍了iOS 自定义表格视图单元格标签调整大小损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing an iOS app for a client, the main view is a table view, and i fill the cells with text, much like most iOS twitter clients.

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

I have created a custom cell view with 3 labels, and i fill these labels with the texts. One of the labels needs to resize automatically depending on the amount of text there is (maximum of 140 characters).

这很好用,直到我向上/向下滚动列表,当文本扩展到单个整行(如标签已扩展)或仅占用部分空间,因此它最终会更深并溢出到其他标签中(我确实根据另一个类似的 SO 问题启用了剪辑子视图")

This works fine until i scroll up/down the list when the text either extends to a single full line (like the label has expanded) OR only takes up part of the space so it ends up deeper and overflowing into other labels (i do have "Clip Subviews" enabled as per another similar SO question)

所以当表和它的数据第一次加载时,屏幕看起来像:

So when the table and its data is first loaded the screen looks like:

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

在稍微滚动之后它看起来像:

And after a bit of scrolling it looks like:

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

因此似乎标签在滚动期间正在调整大小(可能是由于重复使用了相同的单元格?)并且没有调整回正确的大小.

So it seems that the label is resizing during the scrolling (maybe due to the same cell being reused?) and not resizing back to the correct size.

我填充单元格的代码是:

My code for filling a cell is:

-(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;
}

所以我要问的是,是什么导致了这个问题?以及如何解决?

So what i am asking is, what is causing this problem? and how can it be solved?

推荐答案

sizeToFit 方法的行为可能很奇怪,因为每次 cellForRowAtIndexPath 都会更改 UILabel 框架被称为.

The sizeToFit method might be behaving in a weird way because the UILabel frame is changed every time cellForRowAtIndexPath is called.

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

One thing you can try is setting the frame of the label object back to the original size (the valeu set in the NIB file) right before calling sizeToFit

[label setFrame:CGRectMake(0.0f, 0.0f, 100.0f, 50.0f)];    
[label sizeToFit];

这篇关于iOS 自定义表格视图单元格标签调整大小损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆