OGeek|极客世界-中国程序员成长平台

标题: ios - 重复添加 subview 到 `UITableViewCell` [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 09:53
标题: ios - 重复添加 subview 到 `UITableViewCell`

我使用自定义编辑操作,然后在按下操作后通过 indexPath 编辑行

-(NSArray *)tableViewUITableView *)tableView editActionsForRowAtIndexPathNSIndexPath *)indexPath {

    UITableViewRowAction *DeleteButton = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title"Delete" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath)
    {
      UITableViewCell *cell = (UITableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
      UISwitch *Switch = [[UISwitch alloc] initWithFrame: CGRectMake(0,0,0,0)];
      [cell.contentView addSubview:Switch];
    }];

 return @[DeleteButton];
}

这会在按下 Delete 操作按钮的单元格中添加一个 UISwitch然而它每 12 行左右重复一次;所有索引路径都不同(0-1)-(0-2)..etc.

我个人认为这是由于本行抓取单元格的方法造成的
UITableViewCell *cell = (UITableViewCell*)[tableView cellForRowAtIndexPath:indexPath];



Best Answer-推荐答案


按照设计,当单元格从屏幕顶部滚动出来并且新单元格从底部向上滚动时,单元格会被重复使用。除非您明确选择退出此行为,否则它将准确解释您所观察到的内容。如果您在可见的单元格上设置任何属性(无论是标签上的文本,还是添加 subview ),则需要取消这些更改,以便在“重新使用单元格”时"或回收,修改在您不期望或不希望的上下文中仍然不可见。

解决此问题的一个方法是使用 UITableViewCell 的自定义子类,而不是将您的切换 subview 添加到标准 UITableViewCell。您将为自定义子类提供一个属性,其中引用您在 rowAction 方法中添加的 subview 开关。此引用使您能够在以后删除或隐藏它。

您可以考虑将开关设置为始终存在于您的自定义单元格的 contentView 中的 subview ,但它会根据操作方法的需要隐藏或显示。

在您的子类中,您将覆盖 -prepareForReuse 方法,并且您可以从自定义单元格的内容 View 中删除或隐藏 subview ,以准备单元格在新的上下文中呈现(例如当您不期望它时,没有添加的开关。)

创建自定义单元子类:

@interface SampleCellTableViewCell : UITableViewCell

@property (weak, nonatomic) UISwitch *aSwitch;

@end

@implementation SampleCellTableViewCell

- (void)prepareForReuse
{
    [[self aSwitch] removeFromSuperview];
    [self setaSwitch:nil];
}

@end

在您的操作方法中,分配属性:

-(NSArray *)tableViewUITableView *)tableView editActionsForRowAtIndexPathNSIndexPath *)indexPath {

    UITableViewRowAction *DeleteButton = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title"Delete" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath)
    {
      SampleTableViewCell *cell = (SampleTableVieCell*)[tableView cellForRowAtIndexPath:indexPath];
      UISwitch *switch = [[UISwitch alloc] initWithFrame: CGRectMake(0,0,0,0)];
      [cell.contentView addSubview:switch];
      [cell setaSwitch:switch];
    }];

 return @[DeleteButton];
}

关于ios - 重复添加 subview 到 `UITableViewCell`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32098379/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4