Learning ios development from scratch (9): Swapping Views

Source: Internet
Author: User

This article is about switching Views, which is also the third method mentioned in the previous article to change the layout after the iphone rotates, first, let's review the three methods mentioned in the previous article. 1. Use Autosizing 2, write code 3, and get a new View to replace the original View.

Switching a View, as its name implies, is to switch between two different views. Therefore, we need at least two views. One View shows the interface when a vertical View gets an iphone, another View displays the interface with the iphone in Landscape. When we rotate the iphone, we switch between the two views. It seems like a user interface is used, in fact, we use two views to replace them. The advantage of doing so is that you don't have to deal with the problem of re-layout complex controls, but the disadvantage is that two different views, we must use two sets of controls, and then when a control is changed, the "same" Control in another View should also be changed (for example, if it is hidden in one View, it should also be hidden in another View, because it is the same interface, this is important .)

Well, let's get started with this study.

1) create a new Single View project and name it Swap

2) Add two buttons and two buttons named Foo and Bar respectively. The length and width are both 125 and the layout is the same as the layout.

3) add another View (landscape view) because this view is a horizontal version of the current view (portrait view), the type, number, and function of the control on the interface should be the same as that of protrait view, the layout is a little different, so the easiest way is to copy a portrait view first, and then layout the widget location on the interface.

Select BIDViewController. xib: In the editor dock of xib, find View, press and hold the option key on the keyboard, select the View, and drag the mouse. A green plus sign appears, then open the mouse under the same layer of the View, so that a View is copied. (Two views may overlap. move the cursor over one View to see two views)

Select the newly added View in the editor dock, switch to Attributes inspector, find Orientation in the Simulated Mertrics column, and change its attribute to Landscape, so that the View will pass.

However, the other button is missing. Because of the button position, the other button is not displayed in the View, we now select the invisible button in the editor dock and set its start point to 10 in the Size inspector. The 10 invisible button shows a new layout.

4) to create the View Outlet, because we want to switch the View, we must specify the View Outlet so that we can operate the View in the code, the method for creating the View Outlet is the same as that for creating the Outlet of other controls. Press the control key, select the View, and drag it to the BIDViewController. h. First, we add the Outlet of the Portrait View and name it the Outlet of the portrait View and the Landscape View.

5) the Outlet Collection for creating a button is slightly different from the previous one. Because we have two views, the buttons in the two views serve the same purpose, therefore, when creating the button Outlet, you can use the Outlet set, that is, the Outlet Collection. The difference between the Outlet Collection and the Outlet is that the Outlet can only correspond to one control, outlet Collection can correspond to multiple controls. In fact, Outlet Collection is an Outlet array, which can store any number of outlets and traverse them one by one. With the Outlet Collection, when writing an Action, we only need to facilitate the Outlet Collection to operate each of the controls contained in it, it will be much more convenient (otherwise you need to declare an Outlet for each control and then operate it one by one, which not only increases the complexity of the code, but also easily misses the control ).

The method for adding an Outlet Collection is the same as that for adding a general Outlet method. Select the button Foo in the Portrait View, hold down the control key, and drag the mouse to the BIDViewController. h. Release the mouse, change the type of Connection in the filled box, change it to "Outlet Collection", name it foos, and click Connect to finish adding. After the addition, switch to the Landscape View, select the Foo button, and Drag control + the mouse to the added Outlet Collection foos. In this way, the Foo button in the Landscape View is also added to the foos Collection.

Use the same method to add an Outlet Collection for the two Bar buttons and name it 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 four buttons. You only need to add one Action and several other buttons to 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) to switch the View, first open the BIDViewController. m file, and add a macro to the top (# import)

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

This macro refers to converting the angle into a radian, which is used when the iphone is rotated, because the Rotation Angle of the iphone is calculated based on the radian, not the angle, therefore, we need to perform a simple conversion. M_PI is a predefined value, that is, 3.14159265358979323846264338327950288

Reload the willAnimateRotationToInterfaceOrientation method and add it to the end of the last @ synthesize, as shown below:

- (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);    }    else if(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(90));        self.view.bounds = CGRectMake(0.0, 0.0, 480.0, 300.0);    }}

The willAnimateRotationToInterfaceOrientation method occurs after the rotation starts but before it is actually rotated, that is, the rotation command has been issued, but the rotation has not yet started.

The above code should be explained in a few places. Let's take an if statement block for description.

Self. view = self. landscape; select the View to Display Based on the iphone's selection direction.

Self. view. transform = CGAffineTransformIdentity; it seems that the rotation status of the view is set to the default state, that is, initialization. This is not very familiar. The online saying is: matrix transformation in linear algebra, this is the constant transformation Transformation When you change a view. you must restore the default state before changing the transform attribute.

Self. view. transform = CGAffineTransformMakeRotation (degreesToRadians (-90); the rotation radians of the view are converted to radians, and then rotated.

Self. view. bounds = CGRectMake (0.0, 0.0, 480.0, 300.0, however, the difference is that the frame control is relative to the parent view, while the bounds is the control's own position, that is, there is no concept relative to the parent view, because we rotate all views, therefore, the starting point is (0.0, 0.0 ).

The preceding rotation method can be used as a template. You can directly copy and paste the method whenever you switch the view.

(I want to explain an extra question. In the above method, I carefully observe the last parameter in CGRectMake. The last parameter is the height of the surface view, but did I find that it is 20 fewer? The reason is the status bar. The height of the status bar on the top of the iphone is 20, so the view height is reduced by 20 .)

8) Implement buttonTappedAction and find buttonTapped in BIDViewController. m. Add the following code:

- (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                                          cancelButtonTitle:@"ok"                                          otherButtonTitles:nil];    [alert show];}

Only this line of code is worth noting.

If ([self. foos containsObject: sender])

Foos is an Outlet Collection object and an NSArray. There is a containObject method in it to check whether an object exists. The above if statement indicates whether the foos contains an object that triggers the buttonTappedAction, that is, whether the Action is triggered by two Foo buttons. If not, even if the two Bar buttons are triggered.

9) Click Foo to compile and run the program. A warning box pops up to show you that the Foo button has been clicked.

Rotate the iphone, click the Bar, and enter the alarm box to show you that the Bar button has been clicked.

Swap 1

10) when updating buttonTapped at the beginning, we said that because two views are switched, changes in one View must also be reflected in another View, here is an example. When you click a button in a View to hide the button, you must also hide the corresponding button in another View and change the buttonTapped Method to the following:

- (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                                          cancelButtonTitle:@"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;        }    }        }

Like foreach in C #, The for statement traverses objects in a set. First, it is determined that the button triggers buttonTapped, then, all objects in the Outlet Collection where the button is located are hidden, which of course hides the buttons in another View.

Compile and run. Click the bar button. The bar button is hidden and rotated to the iphone. The bar button in the other View is also hidden.

 

Swap All

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.