如何在prepareForSegue方法中获取cell.textlabel.text的值?

时间:2014-02-06 23:08:28

标签: ios objective-c uitableview uistoryboardsegue

所以我有一个名为cellNumString的字符串,我在DetailViewController的.h中创建。在我的HistoryTableViewController.m中,我有一个prepareForSegue方法,在其中我将字符串设置为任何东西。现在我有这个:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([[segue identifier] isEqualToString:@"Push"]) {

        HistoryDetailsViewController *detailVC = (HistoryDetailsViewController*)segue.destinationViewController;
        [detailVC setCellNumString:@" cell number"];
    }
}

我想要的只是将@“单元格号”部分改为cell.textlabel.text。但我不能使用细胞。我怎样才能获得cell.textlabel.text的值并将其用作我传递给下一个视图的字符串?

感谢所有帮助,谢谢。

3 个答案:

答案 0 :(得分:3)

如果segue在单元格上,您可以使用此答案https://stackoverflow.com/a/13989915/1835155

您还可以使用以下方式获取所选单元格:

NSIndexPath *selectedIndexPath = [self.tableView indexPathForSelectedRow];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:selectedIndexPath];
NSLog(@"%@", cell.textLabel.text);

答案 1 :(得分:1)

假设您要将字符串设置为选定的单元格,或者您知道要访问其文本标签的单元格,则可以执行以下操作:

//If you want the selected cell    
NSIndexPath *path = [self.tableView indexPathForSelectedRow];
//If you know the cell row index e.g. 1, 2, 3...
NSIndexPath *path = [NSIndexPath indexPathWithIndex:yourRow];
//Create the cell at the index path
UITableViewCell *cell = [tableView cellForRowAtIndexPath:path]
//Do stuff with cell...

答案 2 :(得分:1)

将所选单元格作为发件人参数传递给performSegueWithIdentifier:sender:,如下所示:

[self performSegueWithIdentifier:@"showPromoViewController" sender:cell];

然后在prepareForSegue:sender:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([[segue identifier] isEqualToString:@"Push"]) {

        HistoryDetailsViewController *detailVC = (HistoryDetailsViewController*)segue.destinationViewController;

        // Get the value of cell.textlabel.text
        UITableViewCell *cell = (UITableViewCell *)sender;
        NSString *text = cell.textLabel.text;

        // Pass it to the destination view controller
        [detailVC setCellNumString:text];
    }
}