[IOS7 Summary] 2. data transmission between ViewControllers of the View Controller (1)

Source: Internet
Author: User

Here we use a demo to illustrate how ios transfers important parameters between view controllers. This article first discusses from the handwriting UI, and in the next article we will discuss how to transmit data in the storyboard.

Create an empty project and add a Root View Controller class, as shown in:

#

Add several lines of code to the didFinishLunchingWithOption function, as follows:

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];    // Override point for customization after application launch.    self.window.backgroundColor = [UIColor whiteColor];    [self.window makeKeyAndVisible];        RootViewController *myRootViewController = [[RootViewController alloc] init];    myRootViewController.view.backgroundColor = [UIColor lightGrayColor];    self.window.rootViewController = myRootViewController;    return YES;}

After running, the iOS simulator displays the following results:

 

#

As shown in the figure, the custom myRootViewController is successfully loaded at startup, and a light gray interface is displayed.

Then, create another viewController named FirstSubViewController, and add the following code to the viewDidLoad function of RootViewController:

 

-(Void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view. UIButton * firstVC = [UIButton buttonWithType: UIButtonTypeSystem]; firstVC. frame = CGRectMake (60,244,200, 80); [firstVC setTitle: @ "show next view" forState: UIControlStateNormal]; [firstVC addTarget: self action: @ selector (displayNextViewController) forControlEvents: UIControlEventTouchUpInside]; [self. view addSubview: firstVC];}
Then, you need to define a function named displayNextViewController. The function body is temporarily set to null. When you run the program, a button "show next view" is displayed in the center of the interface, but clicking this button does not respond. This is because the response function displayNextViewController has not been implemented yet. Now add the code to the function:

 

 

- (void)displayNextViewController{    FirstSubViewController *firstSubVC = [[FirstSubViewController alloc] init];    [self presentViewController:firstSubVC animated:YES completion:^{        NSLog(@"present first sub VC ok");    }];}

After the program is run, it is found that the button has a response. After pressing the button, a new white background interface is displayed, which is the firstSubVC defined here;

 

 

The next step is to return the operation on the interface. Create a rollback button in the viewDidLoad function of FirstSubViewController and implement its response function. The Code is as follows:

 

-(Void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view. UIButton * goBack = [UIButton buttonWithType: UIButtonTypeSystem]; goBack. frame = CGRectMake (60,244,200, 80); [goBack setTitle: @ "" forState: UIControlStateNormal]; [goBack addTarget: self action: @ selector (gobacktopreviusviewcontroller) forControlEvents: UIControlEventTouchUpInside]; [self. view addSubview: goBack];}-(void) gobacktopreviusviewcontroller {[self dismissViewControllerAnimated: YES completion: ^ {NSLog (@ "Back to previous OK");}];}

So far, we have switched views through presentViewController and dismissViewController. Next we will consider the issue of data exchange between two view controllers.

 

Previously, a label and text box were added to RootViewController and FirstSubViewController as the data display and input parts. The purpose is to enter a number in FirstSubViewController and then display it in RootViewController.

In these two classes, use property to implement the text box and label bar:

 

//RootViewController.m@interface RootViewController ()@property (strong,nonatomic) UILabel *lable;@end@implementation RootViewController- (UILabel *)lable{    if (!_lable)    {        _lable= [[UILabel alloc] initWithFrame:CGRectMake(60, 150, 200, 30)];        _lable.textAlignment = NSTextAlignmentCenter;        _lable.text = @"Hello World!";        _lable.backgroundColor = [UIColor whiteColor];    }    return _lable;}…..@end//FirstSubViewController@interface FirstSubViewController ()@property (strong,nonatomic) UITextField *inputText;@end@implementation FirstSubViewController- (UITextField *)inputText{    if (!_inputText)    {        _inputText = [[UITextField alloc] initWithFrame:CGRectMake(60, 150, 200, 30)];        _inputText.backgroundColor = [UIColor lightGrayColor];    }    return _inputText;}…..@end


 

Add the following code to the viewDidLoad of the two view controllers:

 

// RootViewController. m-(void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view. [self. view addSubview: self. label]; UIButton * firstVC = [UIButton buttonWithType: UIButtonTypeSystem]; ......} ..... // FirstSubViewController-(void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view. // Add the input box [self. view addSubview: self. inputText]; UIButton * goBack = [UIButton buttonWithType: UIButtonTypeSystem]; ......}

 

Data transmission between view controllers can be performed in a variety of ways. The following experiment is performed one by one:

1. Use the proxy delegate method:

Basic principle: FirstSubViewControllers tries to change the data of RootViewController, but it cannot change the data of other classes except the ability to operate internal data. To pass the data out, you need to set a proxy method to get the class of data in FirstSubViewControllers to follow this method. You can get the data in FirstSubViewControllers by implementing the method in this proxy protocol.

Procedure:

First, define the protocol in FirstSubViewController. h:

 

@protocol FirstSubViewControllerDelegate 
 
  @optional- (void)getStringFromFirstSubViewControllerDelegate:(NSString *)outputString;@end
 

Then add a proxy property that complies with the Protocol:

 

 

@property (nonatomic,weak) id
 
   delegate;
 

In RootViewControlller. h, declare that the class complies with the FirstSubViewControllerDelegate protocol:

 

 

@interface RootViewController : UIViewController
 

After creating a FirstSubViewController instance, define its delegate attribute as self and implement the methods in the Protocol. The two functions are as follows:

 

 

- (void)getStringFromFirstSubViewControllerDelegate:(NSString *)outputString{    self.lable.text = outputString;}- (void)displayNextViewController{    FirstSubViewController *firstSubVC = [[FirstSubViewController alloc] init];    firstSubVC.delegate = self;    [self presentViewController:firstSubVC animated:YES completion:^{        NSLog(@"present first sub VC ok");    }];}

Finally, add a message in gobacktopreviusviewcontroller of FirstSubViewController. m to send the message to the delegate attribute for data retrieval:

 

 

- (void)goBackToPreviousViewController{    [self.delegate getStringFromFirstSubViewControllerDelegate:self.inputText.text];    [self dismissViewControllerAnimated:YES completion:^{        NSLog(@"Back to previous OK");    }];}

 

In this way, the content entered in the input box of FirstSubViewController is displayed on the label of the first interface after pressing the return button.

 

2. How to use Notification

The notification knowledge will be detailed in the future. Here we will briefly introduce a method to use the notification mechanism.

Before using a notification, you must add an "Observer" and notification to the default notification center. The notification is named and the callback method is specified. When the notification center receives a notification from an object, it will call the specified method to perform an operation. The notification sender can also send corresponding messages as notification parameters.

You can add the following function at the end of the viewDidLoad function in RootViewController. m:

 

// Use the notification method to implement [[NSNotificationCenter defacenter center] addObserver: self selector: @ selector (changeLabelText :) name: @ "ChangeLabelTextNotification" object: Nil];
In addition, the callback function of the observer must be implemented:

 

 

- (void)changeLabelText:(NSNotification *)notification{    id text = notification.object;    _lable.text = text;}
The receiving end of this notification has been completed.

 

The sender of the notification only needs to send the notification and parameters according to the predefined name in the corresponding function of "back to the upper-level interface:

 

// Use the notification method to implement [[NSNotificationCenter defacenter center] postNotificationName: @ "ChangeLabelTextNotification" object: _ inputText. text];
Run the command at this time and you will find that it plays the same role as the proxy mode.

 

In addition to proxy and notification, there are other methods, such as KVO, which will be discussed in detail in the future.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.