How can I pass information from one view controlle

2019-08-31 07:52发布

This question already has an answer here:

This is a Q&A Style Post

If I want to pass parameters, such as an NSString, NSArray, or NSDictionary, from one view controller to another, what is the easiest way to do this?

1条回答
女痞
2楼-- · 2019-08-31 08:47

There are multiple ways to achieve this, but two of the cleanest methods would involve passing the parameter(s) into a custom init method for the next view controller, or setting the parameter(s) as a property of the next view controller.

Note that this is not restricted to passing data between view controllers - view controllers are objects and any objects can use the following principles, I'm simply using view controllers for the following examples.

Both of these examples are using a simple UITableViewController as the initial view controller, and the next view controller will be passed the user's selection from a list of cells where they can choose their favorite color, as well as the current date of their selection. This can be done FROM any type of view controller TO any type of view controller with a few minor modifications, and within reason there's really no limit to the types/quantity of information that can be passed this way.

keep in mind that you likely don't want a massive initializer method with 10 parameter names, so in that case you might want to have individual properties and set each one accordingly. You also might want to keep the initialization/setup code to a single line if there's only a few parameters, so using a custom initializer method might be for you in that case.

Demo table view setup

#import "TestTableViewController.h"
#import "NextViewController.h"

@interface TestTableViewController ()

@end

@implementation TestTableViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    self.colors = @[@"Red", @"Orange", @"Yellow", @"Green"];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.colors.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ColorCell"];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ColorCell"];
    }
    cell.textLabel.text = self.colors[indexPath.row];

    return cell;
}

Method #1 - Custom Initializer

NextViewController.h

#import <UIKit/UIKit.h>

@interface NextViewController : UIViewController

// expose the custom initializer so other view controller's can pass in the parameters we want to pass
- (instancetype)initWithFavoriteColor:(NSString *)favoriteColor currentDate:(NSDate *)date;

@end

NextViewController.m

#import "NextViewController.h"

@implementation NextViewController

// implement the custom initializer method
- (instancetype)initWithFavoriteColor:(NSString *)favoriteColor currentDate:(NSDate *)date {
    self = [super init];

    // do whatever you want here with the favorite color string and current date that 
    // was passed in, such as save them to instance variables...

    return self;
}

@end

Implement method #1 in our demo table view:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // get the color they selected for this row from our data source array
    NSString *selectedColor = self.colors[indexPath.row];

    // initialize the next view controller using the handy init method we created
    NextViewController *nextVC = [[NextViewController alloc] initWithFavoriteColor:selectedColor currentDate:[NSDate date]];
    [self.navigationController pushViewController:nextVC animated:YES];
}

Method #2 - Creating/Setting Properties

NextViewController.h

#import <UIKit/UIKit.h>

@interface NextViewController : UIViewController

@property (nonatomic, retain) NSString *favoriteColor;
@property (nonatomic, retain) NSDate *currentDate;

@end

NextViewController.m

#import "NextViewController.h"

@implementation NextViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // do something here with your properties - by the time the view has loaded
    // they will have been set/passed from the original view controller
    self.favoriteColor...
    self.currentDate...
}

@end

Implement method #2 in our demo table view:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // get the color they selected for this row from our data source array
    NSString *selectedColor = self.colors[indexPath.row];

    // initialize the next view controller normally, and set its favorite color property
    // to be what the user selected
    NextViewController *nextVC = [NextViewController new];
    nextVC.favoriteColor = selectedColor;
    nextVC.currentDate = [NSDate date];
    [self.navigationController pushViewController:nextVC animated:YES];
}

In both instances, you have now quickly and easily passed multiple pieces of information from one view controller to another.

查看更多
登录 后发表回答