How to deselect a selected UITableView cell?

前端 未结 24 3124
一整个雨季
一整个雨季 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:15

    If you want to select any table cell with the first click and deselect with the second, you should use this code:

    - (void)tableView:(UITableView *)tableView 
            didSelectRowAtIndexPath:(NSIndexPath *)indexPath {   
    
        if (self.selectedIndexPath && 
            [indexPath compare:self.selectedIndexPath] == NSOrderedSame) {
    
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
             self.selectedIndexPath = nil;
        } 
        else {
            self.selectedIndexPath = indexPath;
        }
    }
    
    0 讨论(0)
  • 2020-12-07 10:15

    Swift 4:

    func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        let cell = tableView.cellForRow(at: indexPath)
        if cell?.isSelected == true { // check if cell has been previously selected
            tableView.deselectRow(at: indexPath, animated: true)
            return nil
        } else {
            return indexPath
        }
    }
    
    0 讨论(0)
  • 2020-12-07 10:18

    What I've found is that on top of setting the cell as selected, you have to let the table view know to select the row at the given index path.

    // Swift 3+  
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if appDelegate.indexPathDelegate.row == indexPath.row {
            self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
            cell.setSelected(true, animated: true)
        }
    }
    
    0 讨论(0)
  • 2020-12-07 10:19

    Swift

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    
        // your code
    
        // your code
    
        // and use deselect row to end line of this function
    
        self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
    
    }
    
    0 讨论(0)
  • 2020-12-07 10:21

    Swift 3/4

    In ViewController:

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

    In Custom Cell:

    override func awakeFromNib() {
        super.awakeFromNib()
        selectionStyle = .none
    }
    
    0 讨论(0)
  • 2020-12-07 10:21

    swift 3.0

        tableView.deselectRow(at: indexPath, animated: true)
    
    0 讨论(0)
提交回复
热议问题