三十而立,从零开始学ios开发(十):Multiview Applications(多个xib之前的切换)

这篇学习的主要内容是Multiview,在我们学习iphone旋转的时候,介绍过多个view的使用方法,不过这里的view和旋转屏幕中所指的多个view是不同的,旋转屏幕中涉及到的多个view是在一个xib文件中的,而我们这里所指的mulitview,则是指多个xib,在多个xib中进行view的切换,也就是从一个xib切换到另一个xib,而每个xib中只有一个view。

另外的一个不同点体现在创建项目的时候,到目前为止,我们创建的所有项目的template都是single view,这次创建的项目将使用新的template。

Multiview applicatin的基本架构,一般来说,一个multiview application会有一个主要的controller来控制view的呈现,这个主要的controller可以是toolbar(iphone上的Safari打开后,地下的一排按钮就是toolbar)或者是tab bar(iphone打开phone,最下面一个一个的tab),或者其他的一些控件,他们控制到底那个view应该显示,那个view应该被隐藏,也就是说,至少需要3个view才能实现view的切换,一个主要的controller view,2个其他的用于切换的view,主要的controller view是一直显示在屏幕上的,而其他的view中,只有1个会显示出来,其他的都被隐藏。ok,下面开始一步一步实现multiview吧,再说下去会越来越糊涂的。

0)项目简介
今天要做的例子中包含3个view,一个controller view,我们会使用toolbar,2个用于切换的view,一个蓝色底,一个黄色底,他们中间都有一个button,单击button会有一个警告框弹出,告诉用户当前显示的是哪个view。

1)创建一个工程,选择Empty Application

这次不再选择Single View Application,而选择Empty Application,项目中的所有文件我们都会手动进行添加。

单击Next按钮,之后的操作和创建Single View项目一样,设定项目名称“View Switcher”,设定项目保存路径,项目创建完成。

2)添加View Controller
由于我们使用的模板是Empty Application,因此当创建完项目后,只有以下一些文件

里面并没有我们需要的controller view,也没有任何xib文件,这些都是需要我们手动添加的。使用快捷键command+N或者菜单栏File>New>New File...,在弹出的窗口中,左边选择Cocoa Touch,右边选择UIViewController subclass,点击Next按钮

填写类名BIDSwitchViewController,其他都是默认选项(注意最后一个checkbox,如果选择了,则将创建一个和BIDSwitchViewController关联的xib文件,我们在这里可以选上,但是为了弄清楚view controller和xib文件是如何关联在一起的,在这个项目中我们暂时不选,后面我们会手动连接这两个文件),点击Next按钮。

选择保持的位置,保存在“View Switcher”目录下,完成创建。

BIDSwitchViewController是项目的最顶层的view controller(root controller),它用于控制另外2个view的切换,下面按照同样的方法,创建另外2个view controller,一个名字教BIDBlueViewController,另一个叫做BIDYellowViewController,他们都不需要关联xib,且都保存在“View Switcher”目录下。创建完成后的“View Switcher”结构如下

3)添加xib文件
使用快捷键command+N或者菜单栏File>New>New File...,在弹出的窗口中,左边选择User Interface,右边选择View,点击Next按钮

Device Family中选择iphone,点击Next

命名为SwitchView.xib,同样保持在“View Switcher”目录下,点击Create,完成创建。

使用同样的方法创建另外两个xib,分别命名为BlueView.xib和YellowView.xib。至此,我们所有的文件都已经创建完毕,整个的“View Switcher”结构图如下

接下来就是写代码的工作了。

4)编辑BIDAppDelegate文件
当一个app启动的时候,我们都会默认的把一个view载入当前的iphone窗口(application's main window),在这个例子中,这个view就是我们的root view,即BIDSwitchViewController。我们是在BIDAppDelegate文件中设置默认载入的view的,因此首先打开BIDAppDelegate.h,添加class BIDSwitchViewController,和它的一个property,如下

#import <UIKit/UIKit.h>
@class BIDSwitchViewController;
@interface BIDAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) BIDSwitchViewController *switchViewController;

@end

其中,@class是告诉BIDAppDelegate,后面的BIDSwitchViewController是一个类,应该以类的方式处理该对象,后面在声明property的时候,BIDAppDelegate就知道BIDSwitchViewController是一个类,不会不认该对象。

接着打开BIDAppDelegate.m,添加如下代码

#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;
}

......

首先import BIDSwitchViewController,然后声明synthesize,对应于头文件中的property。

didFinishLaunchingWithOption方法,当一个app载入完成后需要做一些什么事情,在这里,我们指定了哪个view被载入到windows中作为默认显示的view。

self.switchViewController = [[BIDSwitchViewControlleralloc] initWithNibName:@"SwitchView" bundle:nil];
通过xib(在旧的版本中,xib被称为nib,因此这里出现的是NibName)的名字来制定初始化哪个view

UIView *switchView = self.switchViewController.view;
获取view

CGRect switchViewFrame = switchView.frame;
得到view的frame,也就是这个view的显示位置,在前几篇的文章中提到过这个属性。

switchViewFrame.origin.y += [UIApplicationsharedApplication].statusBarFrame.size.height;
我觉得这句话比较重要,它将view的位置往下移动了20point(point在非retina屏幕中是20px,在retina屏幕中是40px),这样就不会挡住iphone顶部的状态栏了。

switchView.frame = switchViewFrame;
将修改过的frame从新赋值给switchView

[self.window addSubview:switchView];
将switchView设置成window的subview。怎么理解这句话呢,就是说,一个app只有一个窗口(window),这个window只能同时显示一个view,且这个view是基于这个window而存在的,是放在这个window里面的,因此称之为window的subview,子视图。

5)编辑BIDSwitchViewController.h
BIDSwitchViewController是root controller,用于控制其他2个view的切换,因此需要在其头文件中声明其他两个controller,然后需要定义一个Action,用来完成对2个view的切换,将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

代码还是很好理解的,和前面在BIDAppDelegate.h中添加BIDSwitchViewController是一样的。

6)关联BIDSwitchViewController和SwitchView.xib
在Project Navigator中选中SwitchView.xib,在xib的dock中选中File's Owner

然后在Identity inspector中将Class改成BIDSwitchViewController

这样就将SwitchView.xib关联到了BIDSwitchViewController,如果我们选择Connections inspector,会看到我们刚才在BIDSwitchViewController.h中定义的Action:switchViews出现在Received Actions,我们之后就可以将这个Action关联到SwitchView.xib的控件上。

7)在SwitchView.xib上添加Toolbar
在这个例子总,我们切换veiw的方式是点击Toolbar上的一个button,然后切换2个view,SwitchView.xib使我们的root view,因此我们需要在SwitchView.xib上添加一个toolbar,然后点击toolbar上的按钮,切换BlueView.xib和YellowView.xib。

选中SwitchView.xib,在object library中找到Toolbar

拖动到View上,放在最下方

默认的,已经有一个button在Toolbar上了,双击button改变文字,将文字改成“Switch Views”

接着就是将“Switch Views”按钮关联到switchViews,选中“Switch Views”,control-dragged到File's Owner,在弹出的框中选中switchViews

打开Connections inspector,我们可以看到关联后的情况

有一个不同的地方,Toolbar上的button不像一般的button,会有很多的方法让你进行关联,Toolbar上button的Sent Actions(其他的button叫做Send Events,有很多个方法)只有一个方法,而它的作用相当于一般button的touch up inside。

8)关联SwitchView.xib和BIDSwitchViewController's view outlet
BIDSwitchViewController继承自UIViewController,在UIViewController中有一个outlet view,另外当我们在做第6)步的时候,将SwitchView.xib的class改成了BIDSwitchViewController,所以我们要将这个view关联到SwitchView.xib,关联的方法是选中SwitchView.xib,然后选中File's Owner,control-drag到下面的View

释放鼠标后,在填出的框中选则view,这样就关联好了。

关联好后,查看Connections inspector,也可以看到关联后的结果

9)编辑BIDSwitchViewController.m
添加如下代码

#import "BIDSwitchViewController.h"
#import "BIDYellowViewController.h"
#import "BIDBlueViewController.h"

@implementation BIDSwitchViewController
@synthesize yellowViewController;
@synthesize blueViewController;

2个#import这个很好理解,因为BIDSwitchViewController是root controller,会控制另外2个controller,因此需要把另外2个controller引入进来,这样才可以对他们进行操作。
2个synthesize对着头文件中的2个property。

// 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];
}

首先去掉viewDidLoad的注释,然后添加以上的代码。从最后一句可以看出,viewDidLoad方法继承自UIViewController,在这里对其重载,这个方法发生在当view已经载入完成后,我们所要做的是当root view载入完成后,在载入root view的subview,在我们的这个例子中是BlueView。BlueView的载入方法和前面的一样,使用initWithNibName,然后作为subView插入到当前的view中(当前的view就是root view,也就是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];
    }
}

实现switchViews Action,上面的代码还是很好理解的,首先判断当前哪个subview是没有superview的,因为这2个subview不会同时显示,当blueSubview显示时,YellowSubview就会从root view中移除,因此不会具有superview,当得知那个subview没有superview,就说明应该显示这个subview。知道该显示哪个subview后,再判断这个subview是否还存在(是否需要重新载入初始化),然后将另一个subview从superview中移除,再将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;
    }
}

当ios的内存不够用时,didReceiveMemoryWarning会被系统自动调用,来释放可利用的内存。在这里如果哪个subview没有显示,就释放该subview,腾出内存。

至此BIDSwitchViewController的所有代码都写好了,下面就应该处理BIDBlueVeiwController和BIDYellowViewController了。

(友情提示,时不时的编译一下你的project,尽早发现问题,容易修改,否则到后面自己都不知道错在哪里)

10)编辑BlueView.xib和YellowView.xib
分别在BlueView.xib和YellowView.xib上添加一个button,并命名为“Press me”。

修改BlueView.xib的class为BIDBlueViewController,修改YellowView.xib的class为BIDYellowController(修改方法:选中xib,点击File's Owner,在Identity inspector中更改class)
 
class改变了,就需要重新关联一下File's owner的view,方法和之前的一样,选中File‘s Owner,control-drag到下面的View上,在弹出的框中选择view,关联完毕,2个xib都需要进行这个操作。

在Attributes inspector中,将BlueView.xib的background颜色改成蓝色

同样的方法将YellowView.xib的background颜色改成黄色

还有一个地方需要设置,因为我们是在root view中显示这2个subview,而root view有一个toolbar在最下方,因此subview需要把toolbar的位置空出来,再进行自己的布局,还是打开Attributes inspector,在Simulated Metrics栏中有很多现象,他们都是用来模拟iphone屏幕上各种占位控件的,我们将Button Bar的选项设成Toolbar,这样xib就会空出Toolbar的位置来进行布局计算了

仔细看的话,“Press me”按钮的位置往上移动了那么一点点

11)在BIDBlueViewController和BIDYellowViewController中添加代码
在BIDBlueViewController.h中添加Action,如下

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

在BIDBlueViewController.m中实现blueButtonPressed,如下

- (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];
}

在BIDYellowViewController.h添加Action,如下

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

在BIDYellowViewController.m中实现yellowButtonPressed,如下

- (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];
}

代码都很简单,就不多做解释了。

12)关联button和Action
打开BlueView.xib,选中“Press me”按钮,control-drag到File's owner释放,在填出的框中选择blueButtonPressed。
打开YellowView.xib,选中“Press me”按钮,control-drag到File's owner释放,在填出的框中选择yellowButtonPressed。

13)编译运行
至此我们已经可以编译运行程序了,编译成功后,iphone模拟器中显示的效果(“Press me”按钮的效果就不演示了)

按下“Switch Views”按钮,BlueSubview会切换到YellowSubview

14)更炫的切换view的方法
有没有发现上面切换view效果很无聊,ios中有更炫的切换view的方法,使用动画的方式切换view,打开BIDSwitchViewController.m,重新编辑switchViews方法,如下

- (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];
先可以不用理解这句话的意思,因为我也没有理解,反正这行代码是声明一个animation block,前一个参数是设置animation block的title,后一个参数是设置一个对象,我也搞不清楚是干什么的,大概在以后的学习中会有所了解。

[UIViewsetAnimationDuration:1.25];
设定动画时间,即切换view的时间

[UIViewsetAnimationCurve:UIViewAnimationCurveEaseInOut];
设定动画的运动方式,开始慢,中间快,最后慢,大家开始看ios自己的说明吧。(An ease-in ease-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];
设定切换的样式,一共有4个值可以选:
UIViewAnimationTransitionFlipFromRight
UIViewAnimationTransitionFlipFromLeft
UIViewAnimationTransitionFlipCurUp
UIViewAnimationTransitionFlipCurDown
这个大家自试试就可以知道了

[UIViewcommitAnimations];
当所有动画的值设置完毕后,提交动画,之后view就会按照设定的动画进行view的切换了。

(此图截于书本,因此不同清晰)

15)总结
ok,所有的功能都已经完成了,在这个例子中,我们使用toolbar来完成对不同view的切换,我们需要一个root view进行总的控制,然后多个subview进行切换,最后还使用一个比较炫的效果进行view之间的转换,内容很充实!

View Switcher

 

 

 

 

 

 

 

 

posted @ 2012-12-11 00:35  minglz  阅读(17062)  评论(42编辑  收藏  举报