Learning ios development from scratch (10): Multiview Applications (switching before multiple xib instances)

Source: Internet
Author: User
Tags overview example

The main content of this study is Multiview. When we learn how to use multiple views during iphone rotation, the view here is different from the multiple views in the rotating screen, multiple Views involved in rotating the screen are in one xib file, while mulitview we refer to here refers to multiple xib, which switches views among multiple xib, that is, switch from one xib to another, and each xib has only one view.

Another difference is that when a project is created, the templates of all the projects we have created so far are single views. The newly created project will use the new template.

The basic architecture of Multiview applicatin. Generally, a multiview application has a main controller to control the display of the view. The main controller can be a toolbar (After Safari on the iphone is opened, A row of buttons in the ground is a toolbar, a tab bar (the iphone opens the phone, the bottom is a tab), or some other controls. They control the view to be displayed, the view should be hidden. That is to say, at least three views are required for switching. One major controller view and two other views are used for switching, the main controller view is always displayed on the screen, while only one of the other views is displayed, and others are hidden. OK. Let's start to implement multiview step by step. It will become increasingly confusing.

0) The Project Overview example today includes three views, one controller view. We will use toolbar, two views for switching, one blue bottom and one yellow bottom, they all have a button in the middle. clicking the button will bring up a warning box to tell the user which view is currently displayed.

1) create a project and select Empty Application this timeNo longerSelect Single View Application, and selectEmpty ApplicationAll files in the project will be manually added.

Click the Next button. After that, set the project name "View Switcher", set the Project SAVE path, and the project is created.

2) Add View Controller because the template we use is Empty Application, after creating the project, only the following files do not have the controller view we need, nor any xib files, these are all manually added. Use the shortcut key command + N or the menu bar File> New File.... In the displayed window, select Cocoa Touch on the left, UIViewController subclass on the right, and click Next.

Enter the class name BIDSwitchViewController, and the others are the default options (note that the last checkbox is used. If yes, an xib file associated with BIDSwitchViewController will be created. We can choose here, but to figure out how the view controller and xib files are associated, we will not select them in this project, and we will connect them manually later), click the Next button. Select the hold location and save it in the "View Switcher" directory to complete the creation.

BIDSwitchViewController is the top-level view controller (root controller) of the project. It is used to control switching between the other two views. The following describes how to create two other view controllers in the same way, one name is BIDBlueViewController, and the other is BIDYellowViewController. They do not need to be associated with xib and are stored in the "View Switcher" directory. The "View Switcher" structure after creation is as follows:

3) Add the xib File and use the shortcut key command + N or the menu bar File> New File.... In the displayed window, select User Interface on the left, View on the right, and click Next.

Select iphone in Device Family and click Next

Name it SwitchView. xib and keep it in the "View Switcher" directory. Click Create to complete the creation. Create two other xib instances in the same way and name them BlueView. xib and YellowView. xib respectively. So far, all our files have been created. The entire "View Switcher" structure is as follows: the next step is to write code.

4) edit the BIDAppDelegate file. When an app is started, a view is loaded into the current iphone window (application's main window) by default. In this example, this view is our root view, namely, BIDSwitchViewController. We set the default loaded view in the BIDAppDelegate file, so first open BIDAppDelegate. h, add class BIDSwitchViewController, and a property of it, as shown below:

#import <UIKit/UIKit.h>@class BIDSwitchViewController;@interface BIDAppDelegate : UIResponder <UIApplicationDelegate>@property (strong, nonatomic) UIWindow *window;@property (strong, nonatomic) BIDSwitchViewController *switchViewController;@end

Here, @ class tells BIDAppDelegate that the BIDSwitchViewController is a class and should process the object in the class mode. when the property is declared later, BIDAppDelegate will know that BIDSwitchViewController is a class, this object is not recognized.

Next, open BIDAppDelegate. m and add the following code:

#import "BIDAppDelegate.h"#import "BIDSwitchViewController.h"@implementation BIDAppDelegate@synthesize window = _window;@synthesize switchViewController;- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];    // Override point for customization after application launch.        self.switchViewController = [[BIDSwitchViewController alloc] initWithNibName:@"SwitchView" bundle:nil];    UIView *switchView = self.switchViewController.view;    CGRect switchViewFrame = switchView.frame;    switchViewFrame.origin.y += [UIApplication sharedApplication].statusBarFrame.size.height;    switchView.frame = switchViewFrame;    [self.window addSubview:switchView];        self.window.backgroundColor = [UIColor whiteColor];    [self.window makeKeyAndVisible];    return YES;}......

First import BIDSwitchViewController, and then declare synthesize, which corresponds to the property in the header file.

The didFinishLaunchingWithOption method specifies the view to be loaded to windows as the default display after an app is loaded.

Self. switchViewController = [[BIDSwitchViewControlleralloc] initWithNibName: @ "SwitchView" bundle: nil]; through xib (in the old version, xib is called nib, so here NibName appears) to determine which view to initialize.

UIView * switchView = self. switchViewController. view; get view

CGRect switchViewFrame = switchView. frame; obtain the view frame, which is the display position of the view. This attribute is mentioned in previous articles.

SwitchViewFrame. origin. y + = [UIApplicationsharedApplication]. statusBarFrame. size. height; I think this sentence is more important. It moves the position of the view 20 points down (the point is 20px in the non-retina screen and 40px In the retina screen ), this will not block the status bar on the top of the iphone.

SwitchView. frame = switchViewFrame; assign a new value to the modified frame

[Self. window addSubview: switchView]; Set switchView to subview of window. How can we understand this sentence? That is to say, an app only has one window. This window can only display one view at the same time, and this view exists based on this window, is placed in the window, so it is called the subview of the window, subview.

5) EDIT BIDSwitchViewController. h BIDSwitchViewController is the root controller used to control switching between the other two views. Therefore, you need to declare the other two controllers in the header file, and then define an Action, used to switch two views. h:

#import <UIKit/UIKit.h>@class BIDBlueViewController;@class BIDYellowViewController;@interface BIDSwitchViewController : UIViewController@property (strong, nonatomic) BIDBlueViewController *blueViewController;@property (strong, nonatomic) BIDYellowViewController *yellowViewController;- (IBAction)switchViews:(id)sender;@end

The code is quite understandable, just like adding BIDSwitchViewController in BIDAppDelegate. h.

6) Associate BIDSwitchViewController and SwitchView. xib. Select SwitchView. xib in Project Navigator, and select File's Owner in xib's dock.

Then, change the Class in Identity inspector to BIDSwitchViewController so that SwitchView can be changed. xib is associated with BIDSwitchViewController. If we select Connections inspector, we can see that we are in BIDSwitchViewController. action: switchViews defined in h appears in Received Actions. Then we can associate this Action with SwitchView. xib control.

7) in SwitchView. add a Toolbar on the xib. In this example, we switch to veiw by clicking a button on the Toolbar, and then switch to two views, SwitchView. xib enables our root view, so we need to go to SwitchView. add a toolbar on xib, and click the button on the toolbar to switch to BlueView. xib and YellowView. xib.

Select SwitchView. xib: Find the Toolbar in the object library and drag it to the View. put it at the bottom of the default, there is already a button on the Toolbar. Double-click the button to change the text, change the text to "Switch Views" and then associate the "Switch Views" button to switchViews. Select "Switch Views" and control-dragged to File's Owner, in the pop-up box, select switchViews to open Connections inspector. We can see that the associated conditions are different. The buttons on the Toolbar are not like General buttons, there will be many ways for you to associate. on the Toolbar, The Sent Actions of the button (other buttons are called Send Events and there are many methods) has only one method, the function is equivalent to the touch up insi of a general button. De.

8) Associate SwitchView. xib and BIDSwitchViewController's view outlet BIDSwitchViewController inherit from UIViewController. In UIViewController, there is an outlet view, and when we are doing step 6th, we will switch SwitchView. the class of xib is changed to BIDSwitchViewController, so we need to associate this view with SwitchView. xib. The associated method is to select SwitchView. xib, select the File's Owner, control-drag, and release the mouse in the following View. Select view in the filled box, and then associate the View. After Association, view Connections inspector and view the association result.

9) EDIT BIDSwitchViewController. m and add the following code:

#import "BIDSwitchViewController.h"#import "BIDYellowViewController.h"#import "BIDBlueViewController.h"@implementation BIDSwitchViewController@synthesize yellowViewController;@synthesize blueViewController;

2 # import is easy to understand, because BIDSwitchViewController is the root controller and will control the other two controllers. Therefore, you need to introduce the other two controllers to perform operations on them. The two synthesize pairs correspond to the two properties in the header file.

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.- (void)viewDidLoad{    self.blueViewController = [[BIDBlueViewController alloc] initWithNibName:@"BlueView" bundle:nil];    [self.view insertSubview:self.blueViewController.view atIndex:0];    [super viewDidLoad];}

First, remove the comments of viewDidLoad and add the above Code. The last sentence shows that the viewDidLoad method inherits from UIViewController and is reloaded here. This method occurs when the view has been loaded, what we need to do is to load the subview of the root view after the root view is loaded. In our example, It is BlueView. The loading method of BlueView is the same as the previous one. Use initWithNibName and insert it as a subView to the current view (the current view is the root view, that is, SwitchView ).

- (IBAction)switchViews:(id)sender{    if(self.yellowViewController.view.superview == nil) {        if(self.yellowViewController == nil) {            self.yellowViewController = [[BIDYellowViewController alloc] initWithNibName:@"YellowView" bundle:nil];        }        [blueViewController.view removeFromSuperview];        [self.view insertSubview:self.yellowViewController.view atIndex:0];    } else {        if (self.blueViewController ==nil) {            self.blueViewController = [[BIDBlueViewController alloc] initWithNibName:@"BlueView" bundle:nil];        }        [yellowViewController.view removeFromSuperview];        [self.view insertSubview:self.blueViewController.view atIndex:0];    }}

The code above implements switchViews Action is well understood. First, determine which subview does not have superview, because the two subviews are not displayed at the same time. When blueSubview is displayed, yellowSubview will be removed from the root view, so there will be no superview. When we know that the subview does not have a superview, it indicates that this subview should be displayed. After knowing which subview to display, determine whether the subview still exists (whether to re-load and initialize it), remove the other subview from the superview, and display the subview.

- (void)didReceiveMemoryWarning{    // Releases the view if it doesn't have a superview.    [super didReceiveMemoryWarning];        // Release any cached data, images, etc that aren't in use.    if (self.blueViewController.view.superview == nil){        self.blueViewController = nil;    } else {        self.yellowViewController = nil;    }}

When ios memory is insufficient, didReceiveMemoryWarning is automatically called by the system to release available memory. If the subview is not displayed, the subview is released to free up the memory.

So far, all the code of BIDSwitchViewController has been written. Now we should process BIDBlueVeiwController and BIDYellowViewController.

(Friendly reminder: compile your project from time to identify problems as soon as possible and easily modify them; otherwise, you will not know where the errors are)

10) EDIT BlueView. xib and YellowView. xib, add a button on BlueView. xib and YellowView. xib respectively, and name it "Press me ".

Modify BlueView. the class of xib is BIDBlueViewController, And the YellowView is modified. the class of xib is BIDYellowController (modification method: Select xib, click File's Owner, and change the class in Identity inspector, you need to re-associate the view of the File's owner. The method is the same as before. Select the File's Owner, control-drag to the following View, and select view in the pop-up box, after the association is completed, this operation is required for both xib instances.

In Attributes inspector, change the background color of BlueView. xib to blue. In the same way, change the background color of YellowView. xib to yellow.

You also need to set this parameter because we display the two subviews in the root view, and the root view has a toolbar at the bottom. Therefore, subview needs to leave the position of the toolbar empty, then we can make our own layout and open Attributes inspector. There are many phenomena in the Simulated Metrics column. They are used to simulate various placeholder controls on the iphone screen. We set the Button Bar option to a Toolbar, in this way, xib will empty the Toolbar location for layout calculation. If you look at it carefully, the position of the "Press me" button will move up a little bit.

11) Add code in BIDBlueViewController and BIDYellowViewController and add Action in BIDBlueViewController. h, as shown below:

@interface BIDBlueViewController : UIViewController- (IBAction)blueButtonPressed;@end

Implement blueButtonPressed in BIDBlueViewController. m, as shown below:

- (IBAction)blueButtonPressed{    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Blue View Button Pressed"                                                    message:@"You pressed the button on the blue view"                                                   delegate:nil                                          cancelButtonTitle:@"Yep, I did"                                          otherButtonTitles:nil];    [alert show];}

Add Action in BIDYellowViewController. h, as shown below:

@interface BIDYellowViewController : UIViewController- (IBAction)yellowButtonPressed;@end

Implement yellowButtonPressed in BIDYellowViewController. m, as shown below:

- (IBAction)yellowButtonPressed{    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Yellow View Button Pressed"                                                    message:@"You pressed the button on the yellow view"                                                   delegate:nil                                          cancelButtonTitle:@"Yep, I did"                                          otherButtonTitles:nil];    [alert show];}

The code is very simple, so I will not explain it more.

12) associate the button and Action to open BlueView. xib, select the "Press me" button, control-drag to File's owner, and select blueButtonPressed in the filled box. Open YellowView. xib, select the "Press me" button, control-drag to File's owner, and select yellowButtonPressed in the filled box.

13) Now we can compile and run the program. After the program is compiled successfully, the effects shown in the iphone simulator will not be demonstrated)

Press the "Switch Views" button and BlueSubview will Switch to the YellowSubview

14) Is it boring to switch the view in a more dazzling way? There is a more dazzling way to switch the view in ios. You can use an animation to switch the view and open BIDSwitchViewController. m. re-edit the switchViews method as follows:

- (IBAction)switchViews:(id)sender{        [UIView beginAnimations:@"View Flip" context:nil];    [UIView setAnimationDuration:1.25];    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];        if(self.yellowViewController.view.superview == nil) {        if(self.yellowViewController == nil) {            self.yellowViewController = [[BIDYellowViewController alloc] initWithNibName:@"YellowView" bundle:nil];        }        [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES];        [blueViewController.view removeFromSuperview];        [self.view insertSubview:self.yellowViewController.view atIndex:0];    } else {        if (self.blueViewController ==nil) {            self.blueViewController = [[BIDBlueViewController alloc] initWithNibName:@"BlueView" bundle:nil];        }        [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view cache:YES];        [yellowViewController.view removeFromSuperview];        [self.view insertSubview:self.blueViewController.view atIndex:0];    }    [UIView commitAnimations];}

[UIViewbeginAnimations: @ "View Flip" context: nil]; you do not need to understand the meaning of this sentence because I do not understand it either. Anyway, this line of code declares an animation block, the previous parameter sets the title of the animation block, and the next parameter sets an object. I don't know what it is, so I will understand it later.

[UIViewsetAnimationDuration: 1.25]; sets the animation time, that is, the time when the view is switched.

[UIViewsetAnimationCurve: UIViewAnimationCurveEaseInOut. (An employee-in memory-out curve causes the animation to begin slowly, accelerate through the middle of its duration, and then slow again before completing. this is the default curve for most animations .)

[UIViewsetAnimationTransition: preview forView: self. view cache: YES]; set the switching style. You can select UIViewAnimationTransitionFlipFromRight UIViewAnimationTransitionFlipFromLeft UIViewAnimationTransitionFlipCurUp UIViewAnimationTransitionFlipCurDown for a total of four values.

[UIViewcommitAnimations]; after all animation values are set, submit the animation. Then, the view will be switched Based on the set animation. (This picture is captured in books, so it is different and clear)

15) Conclusion OK: All functions have been completed. In this example, we use the toolbar to switch between different views. We need a root view for overall control, then switch multiple subviews, and use a cool effect to convert between views. The content is full!

View Switcher

Related Article

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.