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

本文介绍了一种优雅地修改iOS13中modalPresentationStyle默认值的方法,通过为UIViewController创建分类,避免在每个presentViewController:animated:completion:前手动设置,简化代码并减少遗漏风险。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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模式
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值