優雅修改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模式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章