如何获取在UITableview中选择的行的标题

时间:2010-12-14 21:14:45

标签: iphone objective-c ios4

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

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

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

但我怎么能得到那一行的标题?

提前致谢

问候

5 个答案:

答案 0 :(得分:54)

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

此代码段检索所选单元格并将其text属性存储在NSString中。


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

答案 1 :(得分:9)

假设您使用的是标准UITableViewCell,则可以使用

获取单元格
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];

然后通过以下方式访问文本属性视图属性:

cell.textLabel.text
cell.detailTextLabel.text

答案 2 :(得分:3)

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

cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
顺便说一下,要使用uitableview的委托方法以外的其他方法访问你的tableview,你必须把它挂在IB中(例如..)

希望有所帮助

答案 3 :(得分:2)

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

然后,您可以通过...

从所选单元格中提取标签文本
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSString *cellLabelText = cell.textLabel.text;
    }

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

答案 4 :(得分:0)

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

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

下面,

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

相关问题