ios - 重复向 `UITableViewCell` 添加 subview

标签 ios objective-c uitableview

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

-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)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.

我个人认为是因为这行抓取cell的方法导致的
UITableViewCell *cell = (UITableViewCell*)[tableView cellForRowAtIndexPath:indexPath];

最佳答案

根据设计,当单元格从屏幕顶部滚动而新单元格从屏幕底部向上滚动时,单元格会被重新使用。除非您明确选择退出此行为,否则它将准确解释您所观察到的内容。如果您在可见的单元格上设置任何属性(无论是标签上的文本,还是在您正在执行的操作中添加 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 *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)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 - 重复向 `UITableViewCell` 添加 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32098379/

相关文章:

ios - 当 UITableView 完成请求数据时得到通知?

ios - JSON Parse iOS Array of Dictionaries 解析成数组只显示 tableview 中的最后一个对象

iOS - NSURLConnection - 请求中字符的正确编码

iphone - 如何让我的应用程序保持超过 10 分钟。在后台?

ios - 如何从 CNContactStore ios 获取 RecordID

ios - 当我有多个 TableView 时如何更改 numberOfRowsInSection?

iphone - 如何防止 UITableViewCell 被移离它自己的部分?

ios - 在应用程序进入后台时中断 SceneKit 场景

ios - 如何解决 "undeclared selector ' forwardGeocoderDidFail :withErrorMessage"warning?

ios - React Native iOS Build in Release 配置在启动屏幕上卡住