Learn iOS development from scratch (10): Multiview applications (switch before multiple xib)

Source: Internet
Author: User

The main content of this study is MultiView, when we learn the iphone rotation, the introduction of a number of view usage, but here the view and rotation screen refers to the multiple view is different, rotating the screen is related to the multiple view is in a xib file, The Mulitview we refer to here refers to multiple xib, which switch between the view in multiple xib, that is, from one xib to the other xib, and only one view in each xib.

Another difference is that when you create a project, the template for all the projects we've created so far is a single view, and the project you created will use the new template.

Multiview applicatin Basic architecture, in general, a Multiview application will have a main controller to control the rendering of the view, The main controller can be toolbar (when safari on the iphone opens, a row of buttons in the ground is toolbar) or tab bar (the iphone opens the phone, the bottom one tab), or some other control, They control the view should show that the view should be hidden, that is, at least 3 view to achieve the view switch, a major controller view,2 a different view for switching, the main controller View is always displayed on the screen, while the other view, only 1 will be displayed, the others are hidden. OK, the following start step by step implementation of MultiView bar, it will be more and more confused.

0) Project Introduction Today's example contains 3 view, a controller view, we will use toolbar,2 to switch between the view, a blue bottom, a yellow bottom, they have a button, click button will have a warning box pops up, Tells the user which view is currently displayed.

1) Create a project, choose empty Application this time no longer Select single View application, and choose Empty Application, All the files in the project will be added manually.

Click the Next button, and then create a single view project, set the project name "View Switcher", set the Project save path, project creation is complete.

2) Add view Controller since we are using the template is empty application, so when the project was created, only the following files do not have the Controller view we need, there is no Xib file, These are all required to be added manually. Use the shortcut key command+n or the menu bar file>new>new File ..., in the pop-up window, select Cocoa Touch on the left, select Uiviewcontroller subclass on the right, click the Next button

Fill in the class name Bidswitchviewcontroller, the other is the default option (Note that the last checkbox, if selected, will create a xib file associated with the Bidswitchviewcontroller, we can choose here, But in order to find out how the view controller and Xib files are linked together, in this project we are temporarily not selected, we will manually connect the two files later, click the Next button. Select the location to keep, save in the "View Switcher" directory, complete the creation.

The Bidswitchviewcontroller is the top-most view controller of the project, which controls the switching of the other 2 view, following the same method, creating an additional 2 view controller, One name teaches Bidblueviewcontroller, and the other is called Bidyellowviewcontroller, and they don't need to be associated xib and are saved in the View switcher directory. The "View switcher" structure after creation is as follows

3) Add Xib file using shortcut key command+n or menu bar file>new>new file ..., in the pop-up window, select User Interface on the left, select View on the right, click Next button

Select iphone in Device family, click Next

Named Switchview.xib, also remain in the "View Switcher" directory, click Create, complete the creation. Use the same method to create an additional two xib, named Blueview.xib and Yellowview.xib, respectively. At this point, all of our files have been created, the entire "View switcher" structure is as follows the next is the work of writing code.

4) Edit Bidappdelegate file when an app is launched, we will default to load a view into the current iphone window (application ' s main window), in this case, the view is our root View, which is bidswitchviewcontroller. We set the default load view in the Bidappdelegate file, so first open BIDAppDelegate.h, add Class Bidswitchviewcontroller, and one of its property, as follows

#import <UIKit/UIKit.h>@class bidswitchviewcontroller; @interface Bidappdelegate:uiresponder <UIApplicationDelegate> @property (Strong, nonatomic) UIWindow *window;  *switchviewcontroller; @end

The @class is to tell Bidappdelegate that the following bidswitchviewcontroller is a class that should be treated as a class, and later when declaring the property, Bidappdelegate know that Bidswitchviewcontroller is a class that does not deny the object.

Then 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, corresponding to the property in the header file.

Didfinishlaunchingwithoption How to do something when an app is loaded, and here we specify which view is loaded into Windows as the default display.

Self.switchviewcontroller = [[Bidswitchviewcontrolleralloc] initwithnibname:@ "SwitchView" bundle:nil]; by Xib (in the old version, Xib is called nib, so here is the name of Nibname) to make the initialization of which view

UIView *switchview = Self.switchViewController.view; Get view

CGRect switchviewframe = switchview.frame; The view frame, which is where the view is displayed, has been mentioned in the previous articles.

SWITCHVIEWFRAME.ORIGIN.Y + = [Uiapplicationsharedapplication].statusbarframe.size.height; I think this is important, it moved the view position down 20point (point on the non-Retina screen is 20px, in the Retina screen is 40px), so it does not block the top of the iphone status bar.

Switchview.frame = Switchviewframe; Assign the modified frame to SwitchView from the new value

[Self.window Addsubview:switchview]; Set the SwitchView to the subview of the window. How to understand this sentence, that is, an app has only one window, this window can only display a view at the same time, and this view is based on this window exists, is placed in this window, So called Window's subview, child view.

5) Edit BIDSwitchViewController.h Bidswitchviewcontroller is the root controller that controls the switching of the other 2 view, so you need to declare the other two controllers in their header file , then you need to define an action to complete the switch to 2 view, and change the BIDSwitchViewController.h to the following

#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 well understood, and the previous addition of Bidswitchviewcontroller in BIDAppDelegate.h is the same.

6) Associate Bidswitchviewcontroller and Switchview.xib select Switchview.xib in Project Navigator, select File ' Owner in Xib's Dock

Then change the class to Bidswitchviewcontroller in the identity inspector This associates the switchview.xib with the Bidswitchviewcontroller, if we choose Connections Inspector, will see the action:switchviews that we just defined in BIDSwitchViewController.h appear in received Actions, We can then associate this action with the Switchview.xib control.

7) On Switchview.xib Add toolbar in this example total, the way we switch veiw is to click on a button on toolbar and then switch 2 view,switchview.xib to make our root view, So we need to add a toolbar on the Switchview.xib and then click on the toolbar button to toggle Blueview.xib and Yellowview.xib.

Select Switchview.xib, in the object library, find toolbar Drag to view, placed at the bottom of the default, there is already a button on the toolbar, double-click the button to change the text, the text changed to "Switch Views "then is to link the" Switch views "button to Switchviews, select" Switch Views ", control-dragged to file's Owner, in the pop-up box selected Switchviews Open Connections Inspector, we can see the correlation after the situation there is a different place, the button on the toolbar is not like the general button, there will be many ways for you to associate, toolbar button on the Sent The actions (the other button called Send Events, there are many methods) have only one method, and it acts as the touch up inside of the general button.

8) associated Switchview.xib and Bidswitchviewcontroller ' s view outlet bidswitchviewcontroller inherit from Uiviewcontroller, There's a outlet view in Uiviewcontroller, and when we're doing the 6th step, Change the Switchview.xib class to Bidswitchviewcontroller, so we'll associate this view to Switchview.xib by selecting Switchview.xib and then selecting file ' S Owner,control-drag to the following view after releasing the mouse, select the view in the filled out box so that it is connected. When you're connected, look at the Connections inspector and see the associated results

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 This is very well understood, because Bidswitchviewcontroller is the root controller and will control the other 2 controllers, so you need to bring in another 2 controllers, This will allow them to operate. 2 synthesize to the 2 properties in the header file.

Implement Viewdidload to does additional setup after loading the view, typically from a nib.-(void) viewdidload{      = [[Bidblueviewcontroller alloc] initwithnibname:@ "Blueview" bundle:nil];    [Self.view InsertSubview:self.blueViewController.view atindex:0 ];    [Super Viewdidload];}

First remove the Viewdidload comment, and then add the above code. As can be seen from the last sentence, the Viewdidload method inherits from the Uiviewcontroller, where it overloads, this method occurs when the view is loaded and finished, we have to do is when the root view loading completes, after loading the root The subview of view, in our example, is Blueview. The Blueview loading method is the same as the previous one, using initwithnibname and then inserting it as a subview into the current view (the current view is root view, which 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];    }

Implementation of the Switchviews Action, the above code is still well understood, first of all to determine which subview is not superview, because the 2 subview will not be displayed at the same time, when the Bluesubview display, Yellowsubview will be removed from root view, so there is no superview, and when you know that Subview does not have Superview, it should show this subview. Once you know which subview to show, then determine if the Subview still exists (if you need to reload the initialization), then remove the other subview from the Superview and then display the Subview.

-(void) didreceivememorywarning{    //Releases the view if it doesn ' t has a superview.    [Super didreceivememorywarning];        Release any cached data, images, etc-aren ' t in use.    if (Self.blueViewController.view.superview = = nil) {        Self.blueviewcontroller = nil;    } else {        Self.yellowviewcontroller =  nil;    }}

When iOS memory is not enough, didreceivememorywarning is automatically called by the system to free up available memory. Here, if any of the subview are not displayed, release the Subview and free up memory.

At this point Bidswitchviewcontroller all the code is written, the following should deal with Bidblueveiwcontroller and Bidyellowviewcontroller.

(Friendship tips, from time to time to compile your project, early detection of problems, easy to modify, otherwise you do not know the wrong where)

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 class to Bidblueviewcontroller, modify Yellowview.xib class to Bidyellowcontroller (Modify method: Select Xib, click File ' s Owner , change class in Identity inspector) class changed, you need to re-associate the file's Owner's view, the same way as before, select file ' s Owner,control-drag to the view below, Select View in the pop-up box, the link is complete, the 2 xib need to do this.

In Attributes inspector, change the background color of blueview.xib to blue the same way you change Yellowview.xib's background color to yellow.

There is another place that needs to be set up because we are showing these 2 subview in Root view, and root view has a toolbar at the bottom, so subview need to empty the toolbar position and then make their own layout, or open attributes inspector, there are many phenomena in the simulated metrics bar, they are used to simulate the various placeholder controls on the iphone screen, we set the button Bar option to toolbar, So that the Xib will be vacated toolbar position for the layout calculation of the position of the "press Me" button to move up a little bit

11) Add code in Bidblueviewcontroller and Bidyellowviewcontroller to add action in BIDBlueViewController.h, as follows

@interface Bidblueviewcontroller:uiviewcontroller-(ibaction) bluebuttonpressed; @end

Implement bluebuttonpressed in BIDBLUEVIEWCONTROLLER.M, as follows

-(ibaction) bluebuttonpressed{    Uialertview *alert = [[Uialertview alloc] initwithtitle:@ "Blue View button Pressed" c1/>message:@ "pressed the button on the Blue View"                                                   delegate:nil                                          cancelbuttontitle:@ "Yep, I did"                                          Otherbuttontitles:nil];    [Alert show];}

Add an action to BIDYellowViewController.h, as follows

@interface Bidyellowviewcontroller:uiviewcontroller-(ibaction) yellowbuttonpressed; @end

Implement yellowbuttonpressed in BIDYELLOWVIEWCONTROLLER.M, as follows

-(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 " C4/>otherbuttontitles:nil];    [Alert show];}

The code is simple enough to explain.

12) Associate button and action open Blueview.xib, select the "Press Me" button, Control-drag to file ' s owner release, and select Bluebuttonpressed in the filled out box. Open Yellowview.xib, select the "Press Me" button, Control-drag to file ' s owner release, and select Yellowbuttonpressed in the filled out box.

13) Compile run now we can compile and run the program, after the successful compilation, the iphone simulator display effect ("Press me" button effect is not demonstrated)

Press "Switch views" button, Bluesubview will switch to Yellowsubview

14) A more dazzling way to switch the view is not found above the switch view effect is very boring, iOS has a more dazzling way to switch view, the use of animation to switch view, Open bidswitchviewcontroller.m and 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.yellow        Viewcontroller = [[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] I        nitwithnibname:@ "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]; Can not understand the meaning of this sentence, because I do not understand, anyway, this line of code is to declare a animation block, the previous parameter is set animation block title, after a parameter is set an object, I also do not know what to do, Probably in the future study will have some understanding.

[uiviewsetanimationduration:1.25]; Set the animation time, that is, the time to switch view

[Uiviewsetanimationcurve:uiviewanimationcurveeaseinout]; Set the motion of the animation, start slow, middle fast, and finally slow, everyone began to look at the iOS own instructions. (An ease-in ease-out curve causes the animation to begin slowly, accelerate through the middle of it duration, and then s Low again before completing. The default curve for most animations.)

[Uiviewsetanimationtransition:uiviewanimationtransitionflipfromright ForView:self.view Cache:yes]; Set the style of the switch, a total of 4 values can be selected: Uiviewanimationtransitionflipfromright uiviewanimationtransitionflipfromleft Uiviewanimationtransitionflipcurup Uiviewanimationtransitionflipcurdown This, everyone, you can find out from the test.

[Uiviewcommitanimations]; When the values of all animations are set, the animation is submitted, and then the view switches to the view according to the set animation. (This picture is truncated in a book, so it is distinct)

15) Summary OK, all the functions have been completed, in this example, we use toolbar to complete the different view of the switch, we need a root view for the total control, and then multiple subview to switch, Finally, the use of a more dazzling effect of the conversion between view, the content is very substantial!

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.