当前位置:编程学习 > 网站相关 >>

笨鸟学iOS开发(3)view制作及切换

 

目的

学习view制作及切换的几种方式

 

 

环境

Mac OS X 10.7.2

Xcode4.2

 

 

详解

在storyboard中创建另一个ViewController并使用Segue切换

在storyboard中再增加一个ViewController。在两个ViewController中各增加一个按钮。右击按钮,在弹出菜单中拖放“Modal”圈圈到另一个ViewController上放手即可。

 

在xib文件中创建另一个ViewController并使用代码手动切换

在工程中添加文件,选择创建“UIViewController subclass”,在向导中勾选“With XIB for user interface”,取名为“SecondViewController”,完成后得到3个文件:"SecondViewController.h"、"SecondViewController.m“、"SecondViewController.xib”。

在xib中添加一个按钮,并为其添加事件处理函数,在函数中增加如下代码以用于退出当前的view回到首页:

 

- (IBAction)exitCurrentView:(id)sender { 

    [self.view removeFromSuperview]; 

在首页的ViewController.h中添加此xib对应的变量,如下所示:

 

@interface ViewController : UIViewController 

    SecondViewController* secondViewController; 

 

背后的切换按钮事件函数代码为:

 

- (IBAction)switchToSecondView:(id)sender { 

    secondViewController=[[SecondViewController new] 

                          initWithNibName:@"SecondViewController" 

                          bundle:nil]; 

    [self.view addSubview:secondViewController.view]; 

 

 

在代码中手动创建View并使用代码手动切换

 

- (IBAction)switchToThirdView:(id)sender { 

    //先创建view 

    thirdView=[[UIView alloc] 

               initWithFrame:self.view.bounds]; 

    thirdView.backgroundColor=[UIColor greenColor]; 

     

    //为view增加控件 

    UIButton* button=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 

    button.frame=CGRectMake(100, 100, 100, 100); 

    [button setTitle:@"回首页" 

            forState:UIControlStateNormal]; 

    [button addTarget:self 

               action:@selector(exitThirdView:) 

     forControlEvents:UIControlEventTouchUpInside]; 

    [thirdView addSubview:button]; 

     

    //将view显示出来 

    //加入动画吧 

    [UIView beginAnimations:@"flipping view" 

                    context:nil]; 

    [UIView setAnimationDuration:1]; 

    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft 

                           forView:self.view 

                             cache:NO]; 

    [self.view addSubview:thirdView]; 

    [UIView commitAnimations]; 

 

- (void)exitThirdView:(id)sender 

    //也加入动画效果 

    [UIView beginAnimations:@"flipping view" 

                    context:nil]; 

    [UIView setAnimationDuration:1]; 

    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight 

                           forView:self.view 

                             cache:NO]; 

    [thirdView removeFromSuperview]; 

    [UIView commitAnimations]; 

 

 

预览

\

 

在线观看本节开发视频

源码下载:/2011/1208/20111208021329479.zip

 

作者 iaki2008
补充:综合编程 , 其他综合 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,