Starting from scratch iOS Development (ix): swapping views

Source: Internet
Author: User

This article is to switch views, is also mentioned in the previous article on the third Way when the iphone changes the layout after the rotation, first review the previous article mentioned in the three ways 1, use autosizing 2, write code 3, re-view, replace the original view

Switching between view, as the name implies, is to switch between two different view, then we need at least 2 view, a view to show when the vertical (Portrait) to take the iphone interface, Another view shows that when the iphone is Landscape, when we rotate the iphone, we switch between the 2 view, giving the user the impression that they are using an interface, in fact we are replacing with 2 view. The benefit of this is that there is no need to deal with complex control re-layout problems, but the downside is that there are 2 different view, we have to use 2 sets of controls, and when one control changes, the "Same" control in another view should also be changed (for example, hidden in a view, It should also be hidden in another view, because it is the same interface, which is important. )

OK, talk less, start this study.

1) Create a new single view project and name swap

2) Add 2 buttons to add 2 buttons, named Foo and bar, each with a length of 125 and a layout like the one

3) Add another view (Landscape view) Since this view is a landscape version of the current view (Portrait view), the type, number, and function of the controls on the interface should be the same as the protrait view, just slightly different on the layout. So the easiest way to do this is to copy a portrait view first and then layout the control position on the interface from the new one.

Select Bidviewcontroller.xib, locate view on the editor dock in Xib, press and hold the option key on the keyboard, select View and drag the mouse, a green plus sign appears, and then release the mouse under the same layer of the view. Such a view will be copied well. (maybe 2 view overlap, move the above view with the mouse, you will see there are 2 view)

Select the new view in the editor dock, then switch to attributes Inspector, find the orientation in the simulated mertrics bar, and change its properties to landscape so the view is over.

But another button is missing, because the button position is not displayed in the view, and we now select the Invisible button in the editor dock and set its starting point to 10,10 in size inspector The Invisible button appears. Re-layout it

4) Create view outlet because we want to switch view, so we have to specify the view's outlet, so we can manipulate the view in the code, create the outlet method of the view, and create the outlet of the other controls. Press the control key, the mouse select View, drag into the BIDViewController.h release, and name it. We first add the Portrait view outlet, named portrait add Landscape View outlet, named landscape

5) Create button outlet Collection is slightly different from the previous one, since we have two view, but the function of the two view buttons is the same, so we can use the outlet collection when we create the outlet of the buttons. That is, Outlet Collection,outlet Collection and Outlet The difference is that Outlet can only correspond to one control, Outlet Collection can correspond to multiple controls, in fact Outlet Collection is an array of outlet that can hold any number of outlet and then iterate through it. With the outlet Collection, when we write the action, we just need to facilitate outlet Collection, it is easy to manipulate each of the controls contained therein (otherwise you need to declare a outlet for each control and then This not only increases the complexity of the code, but also makes it easy to omit the control.

To add outlet collection, just like adding a general outlet method, select the button Foo in the Portrait view, and hold down the control key. Drag the mouse to BIDViewController.h, release the mouse, change the type connection in the filled box to "Outlet Collection", and name Foos, click Connect to complete the Add. Once added, switch to Landscape view, select the Foo button, drag the control + mouse to the added outlet Collection Foos so that the Foo button in landscape View is added to the Foos collection.

Use the same method to add outlet Collection to the two bar buttons and name bars. The completed BIDViewController.h file is as follows

#import <UIKit/UIKit.h>@interface bidviewcontroller:uiviewcontroller@property (Strong, Nonatomic) Iboutlet UIView *portrait; @property (Strong, nonatomic) iboutlet UIView *landscape; @property (Strong, Nonatomic ) iboutletcollection (UIButton) nsarray *Foos; @property (Strong, Nonatomic) iboutletcollection (UIButton) Nsarray * bars; @end      

6) Add action to add action buttontapped to 4 buttons, just add an action, several other buttons connect to this action, the complete BIDViewController.h file is as follows

@interface Bidviewcontroller:uiviewcontroller@property (Strong, nonatomic) iboutlet UIView *portrait;@ Property (Strong, Nonatomic) iboutlet UIView *landscape; @property (strong, Nonatomic) iboutletcollection (UIButton) Nsarray *Foos; @property (Strong, Nonatomic) iboutletcollection (UIButton) Nsarray *bars;-(ibaction) Buttontaped: (ID) sender;  @end       

7) Implement view switch first open the Bidviewcontroller.m file, and then add a macro definition at the top (#import的下面)

#define Degreestoradians (x) (M_PI * (x)/180.0)

The meaning of this macro is to turn the angle into radians, which is used when the iphone spins, because the angle of rotation of the iphone is calculated from the radian, not the angle, so we need to make a simple conversion. M_PI is a pre-defined value, which is 3.14159265358979323846264338327950288

The overloaded Willanimaterotationtointerfaceorientation method is added after the last @synthesize, as follows

- (void) Willanimaterotationtointerfaceorientation: (uiinterfaceorientation) tointerfaceorientation Duration: ( Nstimeinterval) Duration {if (tointerfaceorientation = =uiinterfaceorientationportrait) {Self.view =self.portrait; Self.view.transform =cgaffinetransformidentity; Self.view.transform = Cgaffinetransformmakerotation (Degreestoradians (0)); Self.view.bounds = CGRectMake (0.0,0.0,320.0,460.0); }Elseif (tointerfaceorientation = =Uiinterfaceorientationlandscapeleft) {Self.view =Self.landscape; Self.view.transform =cgaffinetransformidentity; Self.view.transform = Cgaffinetransformmakerotation (Degreestoradians (-90)); Self.view.bounds = CGRectMake (0.0, 0.0, 480.0, 300.0);} Else if (tointerfaceorientation = = uiinterfaceorientationlandscaperight) {self.view = self.landscape; Self.view.transform = cgaffinetransformidentity; self.view.transform = Cgaffinetransformmakerotation ( Degreestoradians)self.view.bounds = CGRectMake (0.0, 0.0, 480.0, 300.0);}} 

The Willanimaterotationtointerfaceorientation method occurs after the start of the rotation but before the actual rotation, that is, the rotation of the command has been issued, but has not yet started to rotate the action.

The above code, there are several places to explain, we take an if statement block to explain

Self. View = selflandscape; Choose which view to display based on the iphone's selection direction

Self. View. Transform = Cgaffinetransformidentity; it seems that the rotation state of the view is set to the default state, that is, initialization, this is not very understanding, The online version of the statement is: linear algebra in the matrix transformation, this is the identity transformation??? When you change a View.transform property, you need to restore the default state before you change it.

Self. View. Transform = cgaffinetransformmakerotation(degreestoradians(-)); the rotation radian of the view, converting the angle to radians, Then rotate.

Self. view. bounds = CGRectMake (0.0, 0.0, 480.0, 300.0); CGRectMake has been explained in the previous article, that is, set the starting point and size, the bounds property is first encountered, it is somewhat similar to frame, but the difference is that the frame control is relative to the location of the parent view, and bounds is the position of the control itself, that is, there is no concept relative to the parent view , because we are all rotating the view, so its starting point is naturally (0.0, 0.0).

The above rotation method can be used as a template, each time you encounter a switch view, you can directly copy and paste the method.

(For an additional question, take a closer look at the last parameter in CGRectMake in this method above, the last parameter is the height of the surface view, but is it not found to be 20 less?) The reason for this is the status bar, where the height of the status bar at the top of the iphone is 20, so the view's height will be reduced by 20. )

8) Implement Buttontappedaction find buttontapped in bidviewcontroller.m, add code as follows

-(Ibaction) buttontaped: (Id) Sender {NSString *message =Nilif ([Self.foos containsobject:sender]) message = @ "foo button Pressed" else@" bar button Pressed " [[Uialertview alloc] initwithtitle:message message:nil delegate:nil cancelbuttontitle:ok " Otherbuttontitles:nil]; [Alert show];                

This code needs to be aware that this is the only line

If([self. Foos containsobject: sender])

Foos is a outlet collection object, which is a nsarray with a Containobject method to see if there is an object, The meaning of the IF statement above is to determine whether the Foos contains the object that triggered the buttontappedaction, that is, if the action is triggered by 2 foo buttons, if not, then even if 2 bar buttons are triggered.

9) Compile Run click Foo, a warning box pops up and tells you that the Foo button is clicked

Rotate the iphone, click Bar, and the same warning box is filled out to tell you that the bar button is clicked

Swap 1

10) Update buttontapped at the beginning, we said, because it is 2 views to switch, so the change in one view should be reflected in another view, we give an example here, when you click a button in a view, hide the button, In the other view, you should also hide the corresponding button, and change the buttontapped method to look like this

-(Ibaction) buttontaped: (Id) Sender {/*    NSString *message = nil;    if ([Self.foos containsobject:sender]) message = @ "Foo button pressed";        else message = @ "Bar button pressed"; Uialertview *alert = [[Uialertview alloc] Initwithtitle:message message : Nil Delegate:nil Cancelbuttont    itle:@ "OK" otherbuttontitles:nil];     [Alert show];* /if ([Self.foos Containsobject:sender]) {for (UIButton *onefoo in  foos) {Onefoo.hidden = YES;} } else {for (UIButton *onebar in bars) {Onebar.hidden = YES;}}}    

The For statement here, like foreach in C #, iterates over an object in a collection, first determining that the button triggered the buttontapped, and then hiding all the objects in the Outlet collection where the button is located. This, of course, hides the button in another view.

Compile run, click Bar button, Bar button is hidden rotate iphone, another view Bar button is also hidden

Swap All

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.