免费开源的iOS开发学习平台

UIViewController介绍:4-使用代码切换控制器

UIViewController之间相互切换,除了使用StoryBoard之外,还可以使用代码的方式来实现控制器之间的切换。使用代码切换控制器之前,需要首先创建目标控制器,然后再调用presentViewController方法来完成控制器的切换。

切换新的控制器

通过代码切换控制器的时候,需要首先创建一个目标控制器对象,然后再使用presentViewController方法进行切换。

- (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^ __nullable)(void))completion;

示例代码如下,当点击屏幕时,切换一个背景为红色的控制器。需要注意的是新的控制器是从屏幕下方向上出现的,这个需要与导航控制器进行区分。

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ 
    UIViewController *newVC = [[UIViewController alloc] init];
    newVC.view.backgroundColor = [UIColor redColor];
    [self presentViewController:newVC animated:YES completion:nil];
}

返回原控制器

当需要返回原控制器时,调用dismissViewControllerAnimated:方法,此时该控制器对象会被销毁。

- (void)dismissViewControllerAnimated: (BOOL)flag completion: (void (^ __nullable)(void))completion;

示例代码如下,当点击屏幕时,切换一个背景为红色的控制器,3秒后自动返回原控制器。

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UIViewController *newVC = [[UIViewController alloc] init];
    newVC.view.backgroundColor = [UIColor redColor];
    [self presentViewController:newVC animated:YES completion:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:newVC completion:nil];
        });
    }];
}

示例代码

https://github.com/99ios/9.1.5