Manually call didSelectRowatIndexPath

前端 未结 5 1434

I am trying to call didSelectRowAtIndexPath programmatically but am having trouble.

[self tableView:playListTbl didSelectRowAtIndexPath:indexPath];
         


        
5条回答
  •  渐次进展
    2020-12-14 17:12

    You need to pass a valid argument, if you haven't declared indexPath in the calling scope then you'll get that error. Try:

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:ROW_YOU_WANT_TO_SELECT inSection:SECTION_YOU_WANT_TO_SELECT]
    [self tableView:playListTbl didSelectRowAtIndexPath:indexPath];
    

    Where ROW_YOU_WANT... are to be replaced with the row and section you wish to select.

    However, you really shouldn't ever call this directly. Extract the work being done inside tableView:didSelectRowAtIndexPath: into separate methods and call those directly.

    To address the updated question, you need to use the indexPathsForSelectedRows method on UITableView. Imagine you were populating the table cell text from an array of arrays of strings, something like this:

    - (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
        {
            UITableViewCell *cell = [tv dequeue...];
            NSArray *rowsForSection = self.sectionsArray[indexPath.section];
            NSString *textForRow = rowsForSection[indexPath.row];
            cell.textLabel.text = textForRow;
            return cell;
        }
    

    Then, to get all the selected text, you'd want to do something like:

    NSArray *selectedIndexPaths = [self.tableView indexPathsForSelectedRows];
    NSMutableArray *selectedTexts = [NSMutableArray array];
    for (NSIndexPath *indexPath in selectedIndexPaths) {
        NSArray *section = self.sectionsArray[indexPath.section];
        NSString *text = section[indexPath.row];
        [selectedTexts addObject:text];
    }
    

    selectedTexts would at that point contain all selected information. Hopefully that example makes sense.

提交回复
热议问题