自定义UITableViewCell,UITableView和allowsMultipleSelectionDuringEditing

4

我在使用iOS 5新功能选择多个单元格时遇到了问题。 应用程序结构如下:

-> UIViewController
---> UITableView
----> CustomUITableViewCell

在这里,UIViewController 既是 UITableView 的委托对象,也是数据源(由于某些要求,我无法使用 UITableViewController,所以采用了 UIViewController)。单元格通过以下代码加载到 UITableView 中。

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomTableViewCell *cell = (CustomTableViewCell*)[tv dequeueReusableCellWithIdentifier:kCellTableIdentifier];
    if (cell == nil)
    {
        [[NSBundle mainBundle] loadNibNamed:@"CustomTableViewCellXib" owner:self options:nil];     
        cell = self.customTableViewCellOutlet;    
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    // configure the cell with data
    [self configureCell:cell atIndexPath:indexPath];    

    return cell;
}

单元格界面已从xib文件创建。特别是,我创建了一个新的xib文件,其中父视图由UITableViewCell元素组成。为了提供自定义,我将该元素的类型设置为CustomUITableViewCell,其中CustomUITableViewCell扩展了UITableViewCell

@interface CustomTableViewCell : UITableViewCell

// do stuff here

@end

代码运行良好。表格中显示了自定义单元格。现在,在应用程序执行期间,我将allowsMultipleSelectionDuringEditing设置为YES,并进入UITableView的编辑模式。它似乎有效。实际上,每个单元格旁边都会出现一个空圆圈。问题是当我选择一行时,空圆圈不改变其状态。理论上,这个圆圈必须从空白变成红色的勾号,反之亦然。看来圆圈仍然停留在单元格的contentView上方。
我已经进行了很多实验。我也检查了下面的方法。
- (NSArray *)indexPathsForSelectedRows

在编辑模式下进行选择时,它会得到更新。它显示正确的选定单元格。

对我来说不太清楚的是,当我尝试使用UITableViewCell而不是自定义单元格时,圆圈会正确地更新其状态。

您有任何建议吗?提前感谢您。

1个回答

5

对于那些感兴趣的人,我已经找到了一个有效的解决方案来修复之前的问题。

问题在于当选择样式为UITableViewCellSelectionStyleNone时,在编辑模式下红色勾选标记不能正确地显示。解决方案是创建一个自定义UITableViewCell并覆盖一些方法。我使用awakeFromNib,因为我的单元格是通过xib创建的。为了达到这个解决方案,我遵循了这两个stackoverflow主题:

  1. multi-select-table-view-cell-and-no-selection-style
  2. uitableviewcell-how-to-prevent-blue-selection-background-w-o-borking-isselected

这里是代码:

- (void)awakeFromNib
{
    [super awakeFromNib];

    self.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"row_normal"]] autorelease];
    self.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"row_selected"]] autorelease];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    if(selected && !self.isEditing)
    {

        return;
    }        

    [super setSelected:selected animated:animated];
}

- (void)setHighlighted: (BOOL)highlighted animated: (BOOL)animated
{
    // don't highlight
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];

}

希望这有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接