gpt4 book ai didi

ios - 使用方法 : prepareForReuse 时遇到问题

转载 作者:行者123 更新时间:2023-11-29 02:19:32 33 4
gpt4 key购买 nike

我有一个自定义的 UITableViewCell,当它被选中时,它会扩展并添加一个 UILabel 到我添加的选定单元格 UIView Storyboard。

当我运行应用程序并选择一个单元格时,标签会按预期添加到 myView 中。问题是,当我向下滚动时,标签也显示在另一个单元格中。

显然,它之所以如此,是因为我正在重复使用电池,但我没有像 Emilie 所说的那样清洁它们。我正在尝试调用 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;
}

最佳答案

答案很简单:你可以像你应该的那样重复使用你的电池,但永远不要清洁它们

重用您的UITableViewCell意味着您之前单击的单元格将在屏幕外时被重用。

单击后,您将向 UITableViewCell 添加一个 View 。重用时, View 仍然存在,因为您从未删除它。

你有两个选择:一个,你可以设置一个 self.info View 的标签(或者检查你保存在内存中的索引路径),然后检查你何时出列单元格是否有信息 View ,以及去掉它。更简洁的解决方案是通过覆盖自定义 UITableViewCell

prepareForReuse 方法来实现 View 删除

精确

初始化后,您需要做的第一件事是为 self.info View 设置一个标签:

[self.info setTag:2222];

如果你想让它尽可能简单,你可以直接在你的 cellForRowAtIndexPath 方法中检查并删除 self.info View :

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;

我不太确定这段代码是否可以编译,我现在无法在我这边测试它。希望它有效!

关于ios - 使用方法 : prepareForReuse 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28330182/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com