iOS 模态视图,视图之间的切换

视图之间的简单切换

    新建一个工程,创建两个类FiretUIViewController和SecondViewController,他们都继承与UIViewController.在每个

类里面,即在这里的每个试图控制器里都写一个如下所示touch方法,这个方法是点击屏幕就能调用,以便我们调试程序:

                -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

还有就是每个视图的颜色都得设置一下,这样方便调试

1.首先在AppDelegate.h文件,导入FiretUIViewController的头文件,代码如下:

 1 #import <UIKit/UIKit.h>
 2 
 3 #import "FirstViewController.h"
 4 
 5 @interface AppDelegate : UIResponder <UIApplicationDelegate>
 6 
 7 @property (strong, nonatomic) UIWindow *window;
 8 
 9 @property(strong,nonatomic)FirstViewController *firstVC;
10 
11 @end

2.其次在AppDelegate.m文件里:

在 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

 }方法里写上两句代码,代码如下:

 1 #import "AppDelegate.h"
 2 
 3 @interface AppDelegate ()
 4 
 5 @end
 6 
 7 @implementation AppDelegate
 8 
 9 //应用程序已经加载完毕
10 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
11     self.firstVC=[[FirstViewController alloc]init];
12     
13     //设置根视图控制器
14     self.window.rootViewController=self.firstVC;
15     return YES;
16 }

3.实现FiretUIViewController到SecondViewController的切换,首先得在FiretUIViewController中导入SecondViewController的头文件,然后在FiretUIViewController.m文件里实现如下代码:

 1 #import "FirstViewController.h"
 2 
 3 @interface FirstViewController ()
 4 
 5 @end
 6 
 7 @implementation FirstViewController
 8 
 9 - (void)viewDidLoad {
10     [super viewDidLoad];
11     self.view.backgroundColor=[UIColor redColor];
12     
13 }
//点击屏幕调用此方法
14 -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 15 { 16 SecondViewController *secondVc=[[SecondViewController alloc] init]; 17 secondVc.modalPresentationStyle=4; 18 [self presentViewController:secondVc animated:YES completion:^{ 19 NSLog(@"从FirstViewController切换到SecondViewController"); 20 //此方法调用会执行这行代码 21 }]; 22 }

这样就实现了FiretUIViewController到SecondViewController的切换,可是这样还不行,因为SecondViewController不能回到FiretUIViewController,所以说我们还得在SecondViewController.m文件里写上返回的方法。

4.首先在SecondViewController文件里导入FiretUIViewController.h头文件,然后SecondViewController.m里实现如下代码:

 1 #import "SecondViewController.h"
 2 
 3 @interface SecondViewController ()
 4 
 5 @end
 6 
 7 @implementation SecondViewController
 8 
 9 - (void)viewDidLoad {
10     [super viewDidLoad];
11     self.view.backgroundColor=[UIColor greenColor];
12 }
13 -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
14 {
15     [self dismissViewControllerAnimated:YES completion:^{
16         NSLog(@"从SecondViewController返回的FirstViewController");
17     }];
18 }

这就实现了从ViewController到FirstViewController得来回转换了。

总结:

要实现视图之间的切换,要在两个视图控制器中分别写如下两个方法。

presentViewController: animated: completion:

dismissViewControllerAnimated: completion:

这两个方法一般是一起使用,才能实现两个视图之间的来回切换。我们暂且说成一个present方法,一个dismiss方法。

posted @ 2016-03-14 20:15  远方的狼  阅读(1042)  评论(0编辑  收藏  举报