如何基于indexPath获取单元格文本?

She*_*lam 19 iphone cocoa-touch objective-c uitabbarcontroller uitableview

我有一个超过5个UITabBarItems的UITabBarController,因此moreNavigationController可用.

在我的UITabBarController委托中,我执行以下操作:

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

UITableView *moreView = (UITableView *)self.tabBarController.moreNavigationController.topViewController.view;
    moreView.delegate = self;
}
Run Code Online (Sandbox Code Playgroud)

我想实现一个UITableViewDelegate,以便我可以捕获所选的行,设置自定义视图属性,然后推送视图控制器:

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

当用户点击一行时,我需要获取单元格的文本.我怎么能做到这一点?

Mih*_*hta 53

- (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;
}
Run Code Online (Sandbox Code Playgroud)

更好的解决方案是维护单元格数组并在此处直接使用它

    // 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;

}
Run Code Online (Sandbox Code Playgroud)

  • 对其他人的注释/警告:`[tableView cellForRowAtIndexPath:...]`!==`[self tableView:tableView cellForRowAtIndexPath:...]`.在我的测试中,后者每次都返回一个单元格的新实例,而前者实际上将返回正在使用的实例(如果存在). (4认同)
  • 为什么维护一个细胞阵列会更好? (3认同)