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

我可以使用-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];
}

你能帮忙吗?


当前回答

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

其他回答

基于saikirans的解决方案,我写了这个,这对我有帮助。在.m文件中:

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

    if(selectedRowIndex && indexPath.row == selectedRowIndex.row) {

        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        selectedRowIndex = nil;

    }

    else {  self.selectedRowIndex = [indexPath retain];   }

    [tableView beginUpdates];
    [tableView endUpdates];

}

在头文件中:

@property (retain, nonatomic) NSIndexPath* selectedRowIndex;

我也不是很有经验,所以双重检查内存泄漏等。

这应该可以工作:

[tableView deselectRowAtIndexPath:indexpath1 animated:NO];

确保materialTable和tableView指向同一个对象。

材料是否连接到接口生成器中的tableView ?

使用这段代码

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
 {
    //Change the selected background view of the cell.
     [tableView deselectRowAtIndexPath:indexPath animated:YES];
 }

斯威夫特3.0:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //Change the selected background view of the cell.
    tableView.deselectRow(at: indexPath, animated: true)
}

斯威夫特2.0:

tableView.deselectRowAtIndexPath(indexPath, animated: true)

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

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