user964627
user964627

Reputation: 665

UITableView DidSelectRowAtIndexPath?

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 the cell?

I already Have:

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

}

Is there a simple line I can use to grab the text out the cell that the user clicks?

Upvotes: 25

Views: 71674

Answers (5)

Joe
Joe

Reputation: 57169

Use UITableView's cellForRowAtIndexPath:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSString *cellText = cell.textLabel.text;
}

Upvotes: 95

Gleb Karpushkin
Gleb Karpushkin

Reputation: 53

Swift Version:

let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
let cellText: String = cell.textLabel.text

Upvotes: 2

PengOne
PengOne

Reputation: 48398

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];
}

Upvotes: 4

Rayfleck
Rayfleck

Reputation: 12106

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

 [myArray addObject: [datasource objectAtIndex:indexPath.row]];

Upvotes: 6

Antwan van Houdt
Antwan van Houdt

Reputation: 6991

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.

Upvotes: 3

Related Questions