我正在做一个项目,我必须预先选择一个特定的单元格。

我可以使用-willDisplayCell预选择一个单元格,但是当用户单击任何其他单元格时,我不能取消选择它。

- (void)tableView:(UITableView*)tableView 
        willDisplayCell:(UITableViewCell*)cell
        forRowAtIndexPath:(NSIndexPath*)indexPath
{ 
    AppDelegate_iPad *appDelegte = 
      (AppDelegate_iPad *)[[UIApplication sharedApplication] delegate];

    if ([appDelegte.indexPathDelegate row] == [indexPath row])
    {
        [cell setSelected:YES];    
    } 
}

- (void)tableView:(UITableView *)tableView 
        didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    AppDelegate_iPad *appDelegte = 
      (AppDelegate_iPad *)[[UIApplication sharedApplication] delegate];

    NSIndexPath *indexpath1 = appDelegte.indexPathDelegate;
    appDelegte.indexPathDelegate = indexPath;
    [materialTable deselectRowAtIndexPath:indexpath1 animated:NO];
}

你能帮忙吗?


当前回答

NSIndexPath * index = [self.menuTableView indexPathForSelectedRow];
[self.menuTableView deselectRowAtIndexPath:index animated:NO];

根据您的代码放置此代码,您将取消选定单元格。

其他回答

在表视图委托的didSelectRowAtIndexpath中使用以下方法(或从任何地方)

[myTable deselectRowAtIndexPath:[myTable indexPathForSelectedRow] animated:YES];

这是Swift 4的解决方案

 in tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)

只需添加

tableView.deselectRow(at: indexPath, animated: true)

这招很管用

例子:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
//some code
}

斯威夫特4:

tableView.deselectRow(at: indexPath, animated: true)

斯威夫特3.0:

遵循ray wenderlich swift风格指南的协议一致性部分,将相关的方法组合在一起,将这个扩展放在你的视图控制器类下面,像这样:

// your view controller
class MyViewcontroller: UIViewController {
  // class stuff here
}

// MARK: - UITableViewDelegate
extension MyViewcontroller: UITableViewDelegate {
      // use the UITableViewDelegate method tableView(_:didSelectRowAt:)
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        // your code when user select row at indexPath

        // at the end use deselectRow
        tableView.deselectRow(at: indexPath, animated: true)
    }
}

试试这个

[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];