How to deselect a selected UITableView cell?

前端 未结 24 3121
一整个雨季
一整个雨季 2020-12-07 10:10

I am working on a project on which I have to preselect a particular cell.

I can preselect a cell using -willDisplayCell, but I can\'t deselect it when t

相关标签:
24条回答
  • 2020-12-07 10:10

    Try this:

    for (NSIndexPath *indexPath in tableView.indexPathsForSelectedRows) {
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
    }
    
    0 讨论(0)
  • 2020-12-07 10:10
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    0 讨论(0)
  • 2020-12-07 10:11

    In addition to setting the cell as selected, you also need to inform the tableView that the cell is selected. Add a call to -tableView:selectRowAtIndexPath:animated:scrollPosition: to your willDisplayCell: method: and you will be able to deselect it as normal.

    - (void)tableView:(UITableView*)tableView 
      willDisplayCell:(UITableViewCell*)cell
    forRowAtIndexPath:(NSIndexPath*)indexPath
    { 
        AppDelegate_iPad *appDelegte = (AppDelegate_iPad *)[[UIApplication sharedApplication] delegate];
    
        if ([appDelegte.indexPathDelegate row] == [indexPath row])
        {
            // SELECT CELL
            [cell setSelected:YES]; 
            // TELL TABLEVIEW THAT ROW IS SELECTED
            [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];   
        } 
    }
    

    Be sure to use UITableViewScrollPositionNone to avoid odd scrolling behavior.

    0 讨论(0)
  • 2020-12-07 10:11

    Swift 2.0:

    tableView.deselectRowAtIndexPath(indexPath, animated: true)
    
    0 讨论(0)
  • 2020-12-07 10:13

    This is a solution for Swift 4

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

    just add

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

    it works like a charm

    example:

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            tableView.deselectRow(at: indexPath, animated: true)
    //some code
    }
    
    0 讨论(0)
  • 2020-12-07 10:15

    Please check with the delegate method whether it is correct or not. For example;

    -(void) tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
    

    for

    -(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    
    0 讨论(0)
提交回复
热议问题