UITableView DidSelectRowAtIndexPath?

前端 未结 5 766
余生分开走
余生分开走 2020-12-23 10:07

I have a table view with a few items (all text). When the user clicks the row I want that text in that cell to be added to an array.

How Do I grab the text out of th

相关标签:
5条回答
  • 2020-12-23 10:49

    Use UITableView's cellForRowAtIndexPath:

    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSString *cellText = cell.textLabel.text;
    }
    
    0 讨论(0)
  • 2020-12-23 10:53

    In general, you can find most answers to questions like this in the Apple documentation. For this case, look under UITableView Class Reference and you will see a section header: Accessing Cells and Sections. This give you the following method:

    – cellForRowAtIndexPath:
    

    Now use this to access the cell, and then use get the text from the cell (if you're unsure how, look under the UITableViewCell Class Reference.

    All together, your method might look something like this:

    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSString *cellText = cell.textLabel.text;
        [myArray addObject:cellText];
    }
    
    0 讨论(0)
  • 2020-12-23 10:58

    Swift Version:

    let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
    let cellText: String = cell.textLabel.text
    
    0 讨论(0)
  • 2020-12-23 11:05

    My first guess would be getting the index, [indexPath row]; then fetching the data from your datasource ( an array or core data ) rather than directly from the table itself.

    0 讨论(0)
  • 2020-12-23 11:09

    It's the inverse of what you did in cellForRowAtIndexPath.

     [myArray addObject: [datasource objectAtIndex:indexPath.row]];
    
    0 讨论(0)
提交回复
热议问题