iOS開發-模式視圖 – iPhone手機開發技術文章 iPhone軟體開發教學課程

在iOS中視圖切換最簡單一個估計就是模式視圖瞭,下面簡單演示一下模式視圖:

1.新建一個空的工程,新建一個MainViewController類和一個SubViewController類

2.在AppDelegate.m中:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    
    MainViewController *mvc = [[MainViewController alloc] init];
    self.window.rootViewController = mvc;
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

3.在MainViewController.m中

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor yellowColor];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(10, 10, 300, 40);
    [button setTitle:@"切換視圖" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)btnClick
{
    SubViewController *svc = [[SubViewController alloc] init];
    svc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;//動畫效果

[self presentViewController:svc animated:YES completion:^{}];//切換到下一個視圖}


4.在SubViewController.m中

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor redColor];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(10, 10, 300, 40);
    [button setTitle:@"返回主視圖" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)btnClick
{
    [self dismissViewControllerAnimated:YES completion:^{}];//返回上一個視圖
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。