Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get textLabel text of selected Cell using the iPhone SDK

Tags:

I would like to know how to get the textLabel string value of the selected uitableviewcell.

like image 842
lab12 Avatar asked Sep 10 '10 14:09

lab12


2 Answers

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
   // now you can use cell.textLabel.text
}
like image 167
Thomas Clayson Avatar answered Sep 20 '22 18:09

Thomas Clayson


You can get the cell using [self.tableView cellForRowAtIndexPath:] and then access its textLabel.text property, but there's usually a better way.

Typically you've populated your table based on some model array that your UITableViewController has access to. So a better way to handle this in most cases is to take the row number of the cell that was selected and use that to find the associated data in your model.

For example, let's say your controller has an array of Buddy objects, which have a name property:

NSArray *buddies;

You populate this array by running a query or something. Then in tableView:cellForRowAtIndexPath: you build a table view cell based on each buddy's name:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BuddyCell"];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BuddyCell"] autorelease];
    }
    cell.textLabel.text = [buddies objectAtIndex:indexPath.row];
    return cell;
}

Now when the user selects a row, you just pull the corresponding Buddy object out of your array and do something with it.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    Buddy *myBuddy = [buddies objectAtIndex:indexPath.row];
    NSLog (@"Buddy selected: %@", myBuddy.name);
}
like image 31
cduhn Avatar answered Sep 18 '22 18:09

cduhn