【问题标题】:How to disable a UITableViewCell but still have interactions with accessory views (i.e UISwitch)如何禁用 UITableViewCell 但仍与附件视图交互(即 UISwitch)
【发布时间】:2013-06-22 19:14:14
【问题描述】:

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

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

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

【问题讨论】:

    标签: ios objective-c uitableview


    【解决方案1】:

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

    并让您的单元格触发 didSelectRowAtIndexPath。

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

    【讨论】:

      【解决方案2】:

      将事件侦听器直接添加到您的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;
          ...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-13
        • 1970-01-01
        相关资源
        最近更新 更多