2010-12-14 87 views
17

我在每个单元格上都有一些名称的tableview,如何在选择行时获得该名称?如何获得在UITableview中选择的行的标题

我知道,我必须使用委托方法

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

,但我怎样才能得到该行的这个称号?

在此先感谢

问候

+0

行没有标题。你想做什么? – 2010-12-14 21:16:12

+0

我的意思是每个单元格在UItableview – appleDE 2010-12-14 21:22:48

回答

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

该片段检索所选单元格,并将其text属性存储在NSString中。


然而,我不推荐这种。最好将数据和表示层分开。使用后台数据存储(例如数组)并使用传入的对象(例如,用于访问数组的索引)中的数据访问它。该数据存储将与用于填充表的数据存储相同。

+0

太棒了!非常感谢。 – iDev 2014-08-05 19:51:42

9

假设你使用的是标准的UITableViewCell,您可以通过使用

UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath]; 

然后通过访问text属性视图属性获取细胞:

cell.textLabel.text 
cell.detailTextLabel.text 
+0

这是做什么? :-) – Eiko 2010-12-14 21:20:13

+0

是的它是做什么的? – appleDE 2010-12-14 21:23:18

+0

(+1)即使是小的错字错误,对我也有用。在代码中它是UITableViewCell,并且您编写了UITableView(但是您在上面的文本中正确地编写了它。 – HpTerm 2012-09-13 21:04:45

2

一旦通过UITableView委托属性将您的某个类注册为委托,您只需实现tableView:didSelectRowAtIndexPath:方法,该方法将在用户选择行时调用。 (有关详细信息,请参见UITableViewDelegate Protocol Reference。)

然后,您可以从中提取选定单元格通过标签文本...

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

..如果这是你需要真的是。

3

您可以使用以下(uitableview-)函数访问uitabelview的每一行:

cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] 

的方式,访问您的tableview其他方法比的UITableView的委托方法,你必须把它挂在IB(例如..)

希望它有助于

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

    NSString *rowTitle=[tableView cellForRowAtIndexPath:indexPath].textLabel.text; 
} 

这里,

[tableView cellForRowAtIndexPath:indexPath]为您提供选定的单元格,然后.textLabel.text为您提供该单元格的标签。