19

我有一个UITabBarController超过5个UITabBarItems,因此moreNavigationController可用。如何根据indexPath获取单元格文本?

在我的UITabBarController委托我做了以下内容:

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

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

我希望实现的UITableViewDelegate这样我就可以捕捉选择该行,设置自定义视图属性,然后推视图控制器:

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

我需要在用户点击一行时获取单元格的文本。我怎样才能做到这一点?

回答

52
- (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; 
} 

更好的解决方案是维持细胞的阵列,并用它直接在这里

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

} 
+3

为什么它更好地保持细胞的阵列? – user592419 2013-05-21 20:01:20

+0

如果您再次调用cellForRowAtIndexPath来捕获选定的单元格,则不必执行整个函数并再次创建单元格。与将已经创建的单元格存储在数组中相比,这会是性能上的昂贵 – 2013-05-22 04:20:17

+0

如果使用insertObject,那么您的数组将很快就会遍布整个地方。该文件称:“如果指数已经被占用,指数及其以外的指标会通过在它们的指数上加1来移动,以腾出空间。”因此,当第二次调用cellForRowAtIndexPath(可能滚动后)时,会插入相同的单元格,但原始单元格和所有其他单元格将在数组中向前推。 – amergin 2013-12-05 19:57:45

相关问题