how to get title of of row selected in UITableview

2020-05-23 08:31发布

问题:

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

回答1:

-(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.



回答2:

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


回答3:

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.



回答4:

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



回答5:

-(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.