6

有没有一种方法可以禁用 UITableViewCell 触发didSelectCellAtIndexPath:委托,同时仍保留使用该单元格附件视图中的 UISwitch 的能力。

我知道你可以设置 cell.userInteractionEnabled = NO,这将禁用单元格,但也会阻止我在附件视图中使用开关。我知道我也可以尝试检测在该didSelectCellAtIndexPath:方法中点击了哪个单元格,但由于我的表格视图是动态的,并且根据用户正在做的事情而变化,这可能会变得混乱。

我正在寻找一种我可以使用的简单而优雅的解决方案。有任何想法吗?

4

2 回答 2

7

如果你不想使用 cell.userInteractionEnabled = NO 那么你设置 cell.selectionStyle = UITableViewCellSelectionStyleNone

并让您的单元格触发 didSelectRowAtIndexPath。

现在在此方法“didSelectRowAtIndexPath”中,您必须通过比较该特定索引处的数据源数组中的对象类型来避免/忽略选择。

于 2013-06-22T19:46:34.337 回答
0

将事件侦听器直接添加到您的UISwitch而不是依赖于didSelectRowAtIndexPath.

-(void)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    // Here I assume you created a subclass MyCell of UITableViewCell
    // And exposed a member named 'switch' that points to your UISwitch

    MyCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];

    if (cell == nil) {
         cell = [[MyCell alloc] init];
         cell.selectionStyle = UITableViewCellSelectionStyleNone; // This could be moved into MyCell class
         [cell.switch addTarget:self action:@selector(switchChanged:) forControlEvent:UIControlEventValueChanged];
    }

    // Now we need some way to know which cell is associated with the switch
    cell.switch.tag = indexPath.row;
}

现在要监听 swich 事件,在同一个类中添加这个方法

-(void)switchChanged:(UISwitch*)switch {
    NSUInteger cellIndex = switch.tag;
    ...
}
于 2013-06-23T02:32:19.907 回答