简体   繁体   中英

didDeselectRowAtIndexPath isn't called

I've implemented the didDeselectRowAtIndexPath method in a UITableView which includes multiple selection.

For some reason, didDeselectRowAtIndexPath is not being called by the delegate. Any suggestions? (I haven't accidentally misspelled didSelectRowAtIndexPath ).

Thanks!

Some things to note about cell selection:

  • didDeselectRowAtIndexPath is only called in a single-selection UITableView if the user clicks a different cell than the one already selected.
  • didSelectRowAtIndexPath is called to select the new row, and didDeselectRowAtIndexPath is called to deselect the previous row
  • In a UITableView with multiple-selection, the previous row is not being deselected, so your deselect is handled in didSelectRowAtIndexPath

You can grab the cell using the delegate method you've implemented and modify it after checking it's selection like so:

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

    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    if (cell.selected) {
        // ... Uncheck
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}

I currently use a tableView with multiple selection, and didDeselectRowAtIndexPath method is calling for me (unlike what is stated in third bullet point in answer above).

I did note that cells that were "preselected", did not call didDeselectRowAtIndexPath correctly unless I did three things:

  1. In cellForRowAtIndexPath, when I find a cell I want to preselect (you might check for matching array entries, or a string like I did), set cell.selected = true for that cell
  2. In cellForRowAtIndexPath, also make a call to method selectRowAtIndexPath for the cell to preselect
  3. In Interface Builder, uncheck the "Show Selection on Touch" checkmark for the tableView. Oddly enough, this was required to ensure that when a preselected item was tapped (ie should be deselected), that didDeselectRowAtIndexPath was called correctly. 在此输入图像描述

Example code:

if productsReceived!.rangeOfString(cell.productName.text!) != nil {
    cell.accessoryType = .Checkmark 
    tableView.selectRowAtIndexPath(indexPath, animated: true,   scrollPosition: UITableViewScrollPosition.None)
    cell.selected = true
}

I hope this helps someone who is trying to implement multiple selection, with preselected cells.

If I'm not mistaken, UITableView doesn't have a built in method for deselecting cells. I believe you need to call deselectRowAtIndexPath: in order for didDeselectRowAtIndexPath to be called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM