简体   繁体   中英

How to transfer data from a UITableViewCell to another UIViewController?

细胞 新视图

How do I transfer data from my UITableViewCell to a UIViewController through a UINavigationController? As an example, what I want to do is transfer the UITableViewCell label name from the cell to the ViewController's label. If you look at the two pictures, you will see what I mean. Also, on another note, how in general do I transfer data from one view to another? Thanks

in Receiver view controller

in .h file

@interface ViewController : UIViewController

@property (strong, nonatomic) NSString      *strDataOfCell;

@end

here make it strong so stays in memory

in table view delegate method

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

    ViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"yourViewIdentifer"];
    NSString *strData = [self.yourArrayOfData objectAtIndex:indexPath.row]; // Here Put your code to Get value from data source array , which is loaded in tableview
    vc.strDataOfCell = strData;
    [self.navigationController pushViewController:vc animated:YES];

}

Hope it helps :)

You can declare properties in the view controller header file you want to transfer. If you navigate through code. You can assign the label to this view controller in table view didSelectRowAtIndexPath. If you navigate through storyboard segue. You can assign the label to this view controller in prepareForSegue:sender:.

代码答案

The answer to my question resides in the "prepareForSegue" method. It's all about manipulating the sender object to send it's data to the next view controller, and the setting next view controller's data based on the sender. I casted the sender to a custom UITableViewCell, took the cell's title, set a navigation controller's rootview to the view controller that was going to receive the data, and boom, gave it the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM