1. 程式人生 > >ios UIViewController頁面跳轉

ios UIViewController頁面跳轉

首先我們要新建2個類,因為我們要實現從第一個頁面跳轉到第二個頁面。第一個叫FirstViewController 繼承自UIViewController.第二個叫SecondViewController,也是繼承自UIViewController.然後給他們加上背景顏色,在BOOL返回值裡面,第一個是藍色,第二個是棕色。

我們先在AppDelegate裡面壓入根檢視控制器,具體程式碼如下。

#import "AppDelegate.h"

#import "FirstViewController.h"//匯入第一個檢視

@interfaceAppDelegate ()

@end

@implementation

AppDelegate

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

self.window = [[UIWindowalloc]initWithFrame:[[UIScreenmainScreen] bounds]];

self.window.backgroundColor = [UIColorwhiteColor];

    //建立檢視控制器

FirstViewController *firstVC = [[

FirstViewControlleralloc]init];

   //設定檢視控制器設為視窗的根檢視控制器

self.window.rootViewController = firstVC;

    [self.windowmakeKeyAndVisible];

returnYES;

}


下面我來設定FirstViewController

#import "FirstViewController.h"

#import "SecondViewController.h"// 匯入要進入的頁面

@interfaceFirstViewController ()

@end

@implementation

FirstViewController

- (void)viewDidLoad {

    [superviewDidLoad];

self.view.backgroundColor = [UIColorblueColor];

    //建立btn按鈕

UIButton *btn = [UIButtonbuttonWithType:UIButtonTypeSystem];

    btn.frame = CGRectMake(20, 30, 250, 40);

    [btn setTitle:@"進入下一個頁面"forState:UIControlStateNormal];

//呼叫下面的btnClick

    [btn addTarget:selfaction:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];

    btn.titleLabel.font = [UIFontsystemFontOfSize:22];

    [self.viewaddSubview:btn];

}

-(void)btnClick

{

//設定要進入的頁面

SecondViewController *secondVC = [[SecondViewControlleralloc]init];

//設定轉變模式,為反轉分格

    secondVC.modalTransitionStyle =   UIModalTransitionStyleFlipHorizontal;

    //現在開啟動畫

    [selfpresentViewController:secondVC animated:YEScompletion:nil];

}



下載已經可以跳入第二個頁面了,那麼我們要怎麼返回呢?下面我來做點事情進入SecondViewController

- (void)viewDidLoad {

    [superviewDidLoad];

//設定背景顏色

self.view.backgroundColor = [UIColorbrownColor];

    //建立一個btn按鈕

UIButton  *btn = [UIButtonbuttonWithType:UIButtonTypeSystem];

    btn.frame = CGRectMake(20, 30, 250, 40);

    [btn setTitle:@"返回頁面"forState:UIControlStateNormal];

    btn.titleLabel.font = [UIFontsystemFontOfSize:22];

    [btn addTarget:selfaction:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:btn];

}

-(void)btnClick

{

//返回到之前的檢視控制器

    [selfdismissViewControllerAnimated:YEScompletion:nil];

}