Starting from scratch to learn iOS development (10): multiview applications (switching before multiple XIB instances)

Source: Internet
Author: User

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) Project Overview
The example to be done today contains 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
Since the template we use is empty application, after the project is created, only the following files are available:

There is no controller view we need, and there is no XIB file, these need to be 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 an XIB File
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, and 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, that is, 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];
Use the name of XIB (in the old version, XIB is called nib, so nibname appears here) to determine which view to initialize

Uiview * switchview = self. switchviewcontroller. view;
Get View

Cgrect switchviewframe = switchview. frame;
The frame of the view, that is, the display position of the view. This attribute is mentioned in the previous articles.

Switchviewframe. Origin. Y + = [uiapplicationsharedapplication]. statusbarframe. Size. height;
I think this sentence is important. It moves the view position down to 20 points (the point is 20px on a non-Retina screen and 40px on a Retina screen ), this will not block the status bar on the top of the iPhone.

Switchview. Frame = switchviewframe;
Assign the modified frame to switchview

[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 the switching of the other two views. Therefore, you need to declare the other two controllers in the header file, and then define an action to switch the two views, set bidswitchviewcontroller. 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 with switchview. XIB
Select switchview. XIB in project navigator, and select File's owner in the dock of XIB.

Then, change the class in identity inspector to bidswitchviewcontroller.

In this way, switchview is enabled. 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) Add a toolbar on switchview. XIB
In this example, we switch Veiw by clicking a button on the toolbar, and then switching two views and 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 and find the toolbar in the object library.

Drag to view and put it at the bottom

By default, there is already a button on the toolbar. Double-click the button to change the text and change the text to "Switch views"

Next, associate the "Switch views" button to switchviews, select "Switch views", control-dragged to file's owner, and select switchviews in the pop-up box.

Open connections inspector. We can see the associated information.

There is a difference that the buttons on the toolbar are not similar to normal buttons. There are many ways for you to associate them. The sent actions of the buttons on the toolbar (other buttons are called send events, there are many methods). There is only one method, and its function is equivalent to the touch up inside of a general button.

8) Associate switchview. XIB and bidswitchviewcontroller's view Outlet
Bidswitchviewcontroller inherits from uiviewcontroller and has an outlet view in uiviewcontroller. In addition, when we do step 6th, we will change the 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, and then select the file's owner, control-drag to the following view

After you release the mouse, select view in the filled box to associate the view.

After Association, view connections inspector and view the association result.

9) EDIT bidswitchviewcontroller. m
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. XIB's class to bidblueviewcontroller, and yellowview. XIB's class to bidyellowcontroller (modification method: Select XIB, click File's owner, and change class in identity inspector)
 
When the class changes, you need to re-associate the view of the file's owner. The method is the same as the previous one. Select File's owner and control-drag to the following view, in the pop-up box, select view. After the association is complete, you need to perform this operation 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 leave the toolbar empty for layout calculation.

If you look at it carefully, the position of the "press me" button is moved up a little bit.

11) Add code to bidblueviewcontroller and bidyellowviewcontroller.
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 button and action
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) Compile and run
Now we can compile and run the program. After the compilation is successful, the effects shown in the iPhone simulator (the effect of the "press me" button will not be demonstrated)

Press the "Switch views" button and bluesubview will switch to the yellowsubview

14) more dazzling Method for switching views
Did you find it boring to switch the view above? There is a more dazzling way to switch the view in iOS, use an animation to switch the view, open bidswitchviewcontroller. m, and re-edit the switchviews method, as shown below:

- (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];
I don't need to understand the meaning of this sentence because I don't understand it either. Anyway, this line of code declares an animation block, and the previous parameter sets the title of the animation block, the next parameter is used to set an object. I don't know what it is, and I will understand it later.

[Uiviewsetanimationduration: 1.25];
Set the animation time, that is, the time when the view is switched.

[Uiviewsetanimationcurve: uiviewanimationcurveeaseinout];
Set the animation movement mode to slow down, fast in the middle, and slow in the end. Let's start watching the IOS instructions. (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: uiviewanimationtransitionflipfromright forview: Self. View cache: Yes];
Set the switching style. A total of four values can be selected:
Uiviewanimationtransitionflipfromright
Uiviewanimationtransitionflipfromleft
Uiviewanimationtransitionflipcurup
Uiviewanimationtransitionflipcurdown
You can see it by yourself.

[Uiviewcommitanimations];
After setting all animation values, 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) Summary
Okay, 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

 

 

 

 

 

 

 

 

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.