我显示在一个组表视图内容解析从XML。我想禁用它上的单击事件(我应该不能单击它)表包含两个组。我只想禁用第一组的选择,而不是第二组。点击第二组的第一行导航到我的管播放器视图。

如何使特定的组或行可选?

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    if(indexPath.section!=0)
    if(indexPath.row==0)    

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:tubeUrl]];   
}

谢谢。


当前回答

如果你想让一行(或行子集)不可选,实现UITableViewDelegate方法-tableView:willSelectRowAtIndexPath:(也被TechZen提到)。如果indexPath不可选,则返回nil,否则返回indexPath。要获得默认的选择行为,只需返回传递给委托方法的indexPath,但也可以通过返回不同的indexPath来更改行选择。

例子:

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // rows in section 0 should not be selectable
    if ( indexPath.section == 0 ) return nil;

    // first 3 rows in any section should not be selectable
    if ( indexPath.row <= 2 ) return nil;

    // By default, allow row to be selected
    return indexPath;
}

其他回答

针对swift 4.0 这样就可以了。 它将禁用didSelectRowAtIndexPath方法中的Cell,但保持子视图可单击。

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
         if (indexPath.row == clickableIndex ) { 
            return indexPath
         }else{
            return nil
        }
    }

我基于数据模型的解决方案:

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    let rowDetails = viewModel.rowDetails(forIndexPath: indexPath)
    return rowDetails.enabled ? indexPath : nil
}

func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
    let rowDetails = viewModel.rowDetails(forIndexPath: indexPath)
    return rowDetails.enabled
}

从iOS 6开始,你可以使用

-tableView:shouldHighlightRowAtIndexPath:

如果您返回NO,它将禁用选择高亮显示和故事板触发的连接到该单元格的segue。

该方法在触摸到一行时被调用。向该消息返回NO将停止选择过程,并且不会导致当前选定的行在触摸停止时失去选定的外观。

UITableViewDelegate协议引用

对于swift 3.0,你可以使用下面的代码禁用用户与UITableView单元格的交互

 cell.isUserInteractionEnabled = false

我喜欢Brian Chapados上面的回答。然而,这意味着你可能在cellForRowAtIndexPath和willSelectRowAtIndexPath中有重复的逻辑,这很容易失去同步。而不是复制逻辑,只需检查selectionStyle:

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.selectionStyle == UITableViewCellSelectionStyleNone)
        return nil;

    else
        return indexPath;
}