优雅修改iOS13的modalPresentationStyle的默认值,一处修改即可

iOS13的modalPresentationStyle默认为UIModalPresentationAutomatic,要想修改,需要手动设置vc.modalPresentationStyle = UIModalPresentationFullScreen;
但是这个修改需要在每个presentViewController:animated:completion:之前加上这样一句代码,需要改动多个文件,多处代码,以后再有页面跳转还需要再加这么一句,太繁琐,容易遗漏。
我们用以下方法就没有那么麻烦了,不需要改变原代码,再有页面跳转,也不用多加代码:

我们为UIViewController建立一个分类,在该分类的.m中加上如下代码

+ (void)load {
    // 方法交换,为的是当系统调用viewDidLoad时候,调用的是我们的my_viewDidLoad方法
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        SEL originalSelector = @selector(viewDidLoad);
        SEL swizzledSelector = @selector(my_viewDidLoad);
        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
        BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
        if (success) {
            class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });
}
 
- (void)my_viewDidLoad {
    
    [self my_viewDidLoad]; // 由于方法交换,实际上调用的是系统的viewDidLoad
    
    NSArray *viewcontrollers=self.navigationController.viewControllers;
    if (viewcontrollers.count > 1) {
        
    } else {
        //present方式
        self.modalPresentationStyle = UIModalPresentationFullScreen;  // 修改默认值
    }
}

使用方法:

UIViewController *vc = [[UIViewController alloc] init];
[self presentViewController:vc animated:YES completion:nil];  // 即使是在iOS13下vc也是全屏显示

修改modalPresentationStyle的值

UIViewController *vc = [[UIViewController alloc] init];
vc.modalPresentationStyle = UIModalPresentationPopover;
[self presentViewController:vc animated:YES completion:nil];  // 不管是在iOS13还是之前版本,都是以UIModalPresentationPopover模式
发布了40 篇原创文章 · 获赞 10 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/ai_pple/article/details/102371835