iOS开发_简化控制器的跳转代码

  • 新建分类
  • UIViewController+GC.h

@interface UIViewController (GC)

// 简化控制器跳转
- (void)push:(id)controller;
// 简化返回
- (void)pop;
// 回到根控制器
- (void)pop_To_Root;

// 简化控制器弹出
- (void)present:(id)controller Finish:(void (^ __nullable)(void))completion;
// 简化消失
- (void)dismiss:(void (^ __nullable)(void))completion;

@end
  • UIViewController+GC.m

@implementation UIViewController (GC)

// 判断一个对象是实例对象还是类对象
- (BOOL)is_Instance:(id)gc_object {
    return [gc_object class] != gc_object;
}

// 简化控制器跳转
- (void)push:(id)controller {
    // 判断一个对象是实例对象
    if ([self is_Instance:controller]) {
        [self.navigationController pushViewController:controller animated:YES];
    }
    else {
        // 是一个类而已
        [self push:[[controller alloc] init]];
    }
}

// 简化返回
- (void)pop {
    [self.navigationController popViewControllerAnimated:YES];
}

// 回到根控制器
- (void)pop_To_Root {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

// 简化控制器弹出
- (void)present:(id)controller Finish:(void (^ __nullable)(void))completion {
    // 判断一个对象是实例对象
    if ([self is_Instance:controller]) {
        BC_Nav_Controller *navController;
        if ([controller isKindOfClass:[BC_Nav_Controller class]]) {
            navController = (BC_Nav_Controller *)controller;
        }
        else {
            navController = [[BC_Nav_Controller alloc] initWithRootViewController:controller];
        }
        navController.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:navController animated:YES completion:completion];
    }
    else {
        // 是一个类而已
        [self present:[[controller alloc] init] Finish:completion];
    }
}

// 简化消失
- (void)dismiss:(void (^ __nullable)(void))completion {
    [self dismissViewControllerAnimated:YES completion:completion];
}

@end
posted @ 2023-03-03 15:42  CH520  阅读(15)  评论(0编辑  收藏  举报