我有一个自定义的UITableViewCell,当它被选中时,它展开并将一个UILabel添加到我在storyBoard中添加的选定单元格UIView中。
当我运行应用程序并选择一个单元格时,标签将按预期的方式添加到myView中。问题是,当我向下滚动时,标签也会显示在另一个单元格上。
很明显,它的行为是这样的,因为我正在重复使用牢房,我没有像埃米莉所说的那样清理它们。我试图调用prepareForReuse的方法和“清理”细胞,但我有困难做到这一点。这是我的代码:
- (void)prepareForReuse {
NSArray *viewsToRemove = [self.view subviews];
for (UILablel *v in viewsToRemove) {
[v removeFromSuperview];
}这样做,甚至可以清除选定的单元格标签.。
- (void)viewDidLoad {
self.sortedDictionary = [[NSArray alloc] initWithObjects:@"Californa", @"Alabama", @"Chicago", @"Texas", @"Colorado", @"New York", @"Philly", @"Utah", @"Nevadah", @"Oregon", @"Pensilvainia", @"South Dekoda", @"North Dekoda", @"Iowa", @"Misouri", @"New Mexico", @"Arizona", @"etc", nil];
self.rowSelection = -1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CategorieCell *customCell = [tableView dequeueReusableCellWithIdentifier:@"cellID" forIndexPath:indexPath];
customCell.title.text = [self.sortedDictionary objectAtIndex:indexPath.row];
return customCell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
CategorieCell *customCell = (CategorieCell *)[tableView cellForRowAtIndexPath:indexPath];
if (self.info) {
[self.info removeFromSuperview];
}
self.info = [[UILabel alloc] init];
[self.info setText:@"Hello"];
[self.info setBackgroundColor:[UIColor brownColor]];
CGRect labelFrame = CGRectMake(0, 0, 50, 100);
[self.info setFrame:labelFrame];
[customCell.infoView addSubview:self.info];
NSLog(@"%ld", (long)indexPath.row);
self.rowSelection = [indexPath row];
[tableView beginUpdates];
[tableView endUpdates];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([indexPath row] == self.rowSelection) {
return 159;
}
return 59;
}发布于 2015-02-04 19:56:51
答案很简单:你可以像你应该的那样重复使用你的细胞,但是永远不要清理它们。
重用您的UITableViewCell意味着您以前单击的单元格将在脱离屏幕时被重用。
单击时,可以向UITableViewCell添加视图。重用时,视图仍然存在,因为您从未删除它。
您有两个选择:第一,您可以设置self.info视图的标记(或者检查内存中保存的索引路径),然后检查是否有info视图对单元格进行排队列,并删除它。更干净的解决方案是通过重写自定义prepareForReuse的UITableViewCell方法来实现视图删除。
精密
您需要做的第一件事是在初始化self.info视图之后为它设置一个标记:
[self.info setTag:2222];如果希望保持尽可能简单,可以直接在self.info方法中检查和删除cellForRowAtIndexPath视图:
CategorieCell *customCell = [tableView dequeueReusableCellWithIdentifier:@"cellID" forIndexPath:indexPath];
customCell.title.text = [self.sortedDictionary objectAtIndex:indexPath.row];
if [customCell.infoView viewWithTag: 2222] != nil {
[self.info removeFromSuperview]
}
return customCell;我并不是百分之一确定这段代码是编译的,我现在还不能在我这一边测试它。希望它能成功!
https://stackoverflow.com/questions/28330182
复制相似问题