How to get cell text based on indexPath?

Sheehan Alam picture Sheehan Alam · May 24, 2010 · Viewed 44.8k times · Source

I have a UITabBarController with more than 5 UITabBarItems so the moreNavigationController is available.

In my UITabBarController Delegate I do the following:

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
//do some stuff
//...

UITableView *moreView = (UITableView *)self.tabBarController.moreNavigationController.topViewController.view;
    moreView.delegate = self;
}

I want to implement a UITableViewDelegate so I can capture the row that was selected, set a custom view property and then push the view controller:

- (void)tableView:(UITableView *)tblView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
  //how can I get the text of the cell here?
}

I need to get the text of a cell when the user taps on a row. How can I accomplish this?

Answer

Mihir Mehta picture Mihir Mehta · May 24, 2010
- (void)tableView:(UITableView *)tblView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
      //how can I get the text of the cell here?
      UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
      NSString *str = cell.textLabel.text;
}

A better Solution is to maintain Array of cell and use it directly here

    // Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    Service *service = [self.nearMeArray objectAtIndex:indexPath.row];
    cell.textLabel.text = service.name;
    cell.detailTextLabel.text = service.description;
    if(![self.mutArray containsObject:cell])
          [self.mutArray insertObject:cell atIndex:indexPath.row];
    return cell;
}



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

    UITableViewCell *cell = [self.mutArray objectAtIndex:indexPath.row];
    NSString *str = cell.textLabel.text;

}