How to programmatically “tap” a UITableView cell?

后端 未结 5 1043
梦如初夏
梦如初夏 2020-12-25 15:23

I was wondering is there a way that I could have my code \"tap\" a cell in my UITableView in order to reproduce the behaviour specified in the - (void)tableView:(UITab

相关标签:
5条回答
  • 2020-12-25 15:38

    if you want to have the cell selected, i.e highlight a specific cell:

    //select first row of first section
    NSIndexPath* selectedCellIndexPath= [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView selectRowAtIndexPath:selectedCellIndexPath animated:false scrollPosition:UITableViewScrollPositionMiddle];
    

    if you want to additionally trigger actions in your didSelectRowAtIndexPath method, you need to manually call the delegate method, it won't happen automatically:

    [self tableView:self.tableView didSelectRowAtIndexPath:selectedCellIndexPath];
    
    0 讨论(0)
  • 2020-12-25 15:42

    It's just a method. Go ahead and invoke it like you'd invoke any other method.

    0 讨论(0)
  • 2020-12-25 15:49

    Can't you put any logic in didSelectRowAtIndexPath into a separate method and just call that method from both didSelectRowAtIndexPath and wherever else you want to call the same code?

    0 讨论(0)
  • 2020-12-25 15:56

    Swift 3.2 Solution

    let indexPath = IndexPath(row: 2, section: 0)  // change row and section according to you
    tblView.selectRow(at: indexPath, animated: true)
    tblView.delegate?.tableView!(tblView, didSelectRowAt: indexPath)
    
    0 讨论(0)
  • 2020-12-25 16:01

    This is a 6.1 update. When you are using segues- all the advice is good, but you also have to invoke the segue. So - to add to the advice and summarize it

    // ... assuming we just added a new row - which is one use of what this thread is trying to do
    
    /* get new count - this is the row we are going to highlight - 0 based */
     int newIndex = [dataArrayUnderlyingTable count]-1; 
    
    /* make it look pretty by highlighting it */
        NSIndexPath *nip = [NSIndexPath indexPathForRow:newIndex inSection:0];
        [[self tableView] selectRowAtIndexPath:nip animated:YES scrollPosition:UITableViewScrollPositionBottom];
    
    /* run the code in the following method so it is not missed */
        [self tableView:[self tableView] didSelectRowAtIndexPath:nip];
    
    /* now 'tap' on it ... or simulate it */
        [self performSegueWithIdentifier: @"viewChildDetails" sender: self];
    
    0 讨论(0)
提交回复
热议问题