how to get title of of row selected in UITableview

2020-05-23 08:29发布

I have tableview with some names on each cell , how can i get that name when select row ?

i know that i have to use delegate method

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

but how can i get that title of that row ?

thanks in advance

regards

5条回答
男人必须洒脱
2楼-- · 2020-05-23 08:59

Once you've registered one of your classes as a delegate via the UITableView delegate property you simply implement the tableView:didSelectRowAtIndexPath: method, which would be called when the user selected a row. (See the UITableViewDelegate Protocol Reference for more information.)

You could then extract the label text from the selected cell via...

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

..if this is really what you require.

查看更多
别忘想泡老子
3楼-- · 2020-05-23 09:05

you can access each row of your uitabelview using the following (uitableview-)function:

cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]

by the way, to access your tableview in other methods than uitableview's delegate method, you have to hook it up in IB (for example..)

hope it helps

查看更多
4楼-- · 2020-05-23 09:13
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
    NSString *cellText = selectedCell.textLabel.text;
}

This snippet retrieves the selected cell and stores its text property in a NSString.


However, I do not recommend this. It is better to keep the data and presentation layers separate. Use a backing data store (e.g. an array) and access it using the data in the passed indexPath object (e.g. the index to use to access the array). This data store will be the same one used to populate the table.

查看更多
冷血范
5楼-- · 2020-05-23 09:13
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

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

Here,

[tableView cellForRowAtIndexPath:indexPath] gives you the selected cell and then the .textLabel.text gives you the label for that cell.

查看更多
小情绪 Triste *
6楼-- · 2020-05-23 09:18

Assuming you're using a standard UITableViewCell, you can get the cell by using

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

then access the text property view properties via:

cell.textLabel.text
cell.detailTextLabel.text
查看更多
登录 后发表回答