重复将子视图添加到“UITableViewCell”

时间:2015-08-19 14:29:40

标签: 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];
}

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

我个人认为这是因为用于抓住此行中的单元格的方法造成的 UITableViewCell *cell = (UITableViewCell*)[tableView cellForRowAtIndexPath:indexPath];

1 个答案:

答案 0 :(得分:1)

按照设计,细胞被重新使用,因为细胞从屏幕顶部滚动,新鲜细胞从底部向上滚动。除非你特别选择退出这种行为,否则它会准确地解释你正在观察的内容。如果在可见的单元格上设置任何属性(无论是标签上的文本,还是正在添加子视图),那么这些更改都需要取消,以便在“重复使用”单元格时“或者回收,在您不期望或不希望的情况下,修改仍然不可见。

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

您可以考虑将切换设置为自定义单元格contentView中始终存在的子视图,但操作方法会隐藏或显示该视图。

在您的子类中,您将覆盖-prepareForReuse方法,并且您将从自定义单元格的内容视图中删除或隐藏子视图,以准备要在新的上下文中呈现的单元格(例如,没有添加的开关当你没想到的时候。)

创建自定义单元格子类:

@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];
}
相关问题