For demo purpose, I will assume we have two view controllers ListViewController
and DetailViewController
. ListViewController has tableview and you have created a segue between your tableview cell and details view controller
.
I'm assuming you are naming it as 'DetailSegue'. Your storyboard should look similar to the below image.
Select the segue between tableViewCell and DetailViewController, open the attributes inspector and specify the identifier as 'DetailSegue'. See the image below,
Run the application now, you should see a smooth navigation from ListViewController to DetailViewController.
Assuming you datasource is an array of stings and you have your datasource and delegate setup already properly for your list tableView
.
Add a method prepareForSegue:sender in your List view controller, this method will get called whenever segue is about to execute.This method will be automatically invoked.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"DetailSegue"]) {
DetailViewController *detailVC = (DetailViewController*)segue.destinationViewController;
NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)sender];
detailVC.title = [self.source objectAtIndex:indexPath.row];
}
}
Add a property called title
in DetailViewController to store the selected title and add another outlet for UILabel to display the title in the view.
DetailViewController.h
#import <Foundation/Foundation.h>
@interface RecipeListViewController : NSObject
@property (weak, nonatomic) NSString *title;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@end
DetailViewController.m
@implementation RecipeListViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.titleLabel.text = self.title;
}
@end
Don't forget to connect the outlet. I hope this gives you an rough idea of how we can pass data between view controllers.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…