我有一个小问题,看起来很经典(在 dequeueReusableCellWithIdentifier 重用时混淆了单元格),但我已经看过类似的问题,但找不到答案。
所以,经典上下文:我有一个 UITableView
, Storyboard中有原型(prototype)单元格,一个带有图像(异步获取),另一个带有 UITextView。
让我们关注文本单元格,因为我在这两个单元格上都遇到了问题,所以我们知道网络不是原因。
当我再次上下滚动时,细胞会混在一起。我认为这是因为我根据 cellForRowAtIndexPath
函数中的数据设置了文本值,但我不确定。
这是我示例中的单元格:
---------------
| 1. "TEXT1" |
---------------
| |
| 2. IMAGE2 |
| |
---------------
| 3. "TEXT3" |
---------------
| 4. "TEXT4" |
---------------
| |
| 5. IMAGE5 |
| |
---------------
我一直向下滚动,一切正常。当我在底部反弹时,单元格 3 和 4 会重新加载(我在 cellForRowAtIndexPath
函数中放置了一个 NSLog)。首先重新加载单元格 4,然后是单元格 3(根据日志)。
问题是,单元格 3 和 4 都以“TEXT3”作为值结束!我的意思是,如果我 NSLog
我在函数中赋予 UITextField.text 的值,它们没有相同的文本值,但在模拟器的屏幕上,它们有..?
这是我的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Getting data for row from indexPath
Data *data = [self.dataArray objectAtIndex:indexPath.row];
NSString *cellIdentifier = [NSString stringWithFormat:@""];
if (data.type == 1) { // Text type
cellIdentifier = @"TextCell";
}
else if (data.type == 2){
cellIdentifier = @"PhotoCell";
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
// Getting various cell elements
if (data.type == 1) {
// Text is 1000
UITextView *textView = (UITextView *)[tableView viewWithTag:1000];
textView.text = data.text;
}
else if (data.type == 2){
//STUFF FOR PHOTO TYPE OF DATA
}
return cell;
}
顺便说一下,我在 iOS6 上的模拟器中遇到这个错误,但在 iOS7 上没有(但也许这只是不同的内存管理..)
非常感谢您的帮助!
最佳答案
我遇到了同样的问题,我就是这样解决的。
在我的 CustomTableViewCell 中,我使用 init 方法为标签等设置值。
所以我在init中添加了这个条件。
代码:
(无效) initWithCellLabelString : (NSString *) cellLabelString {
for (id subview in self.contentView.subviews) { [ subview removeFromSuperview];
//初始化的其余部分
希望对您有所帮助。
编辑 我这样做的更好方法是覆盖自定义 TableView 单元格类中的 prepareForReuse 并将值设置为 nil。这可能不是推荐的方法,但我没有遇到任何性能问题。
关于iphone - 带有文本和图像的 UITableView : mixed up in dequeueReusableCellWithIdentifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19301268/