美文网首页iOS开发
iOS-在任意当前画面弹出Alert

iOS-在任意当前画面弹出Alert

作者: 拎着猫走的鱼 | 来源:发表于2019-06-04 10:44 被阅读0次
    • 首先创建UIAlertController的分类,命名为Window

    • UIAlertController+Window.h

    #import <UIKit/UIKit.h>
    
    @interface UIAlertController (Window)
    
    - (void)show;
    
    - (void)show:(BOOL)animated;
    
    @end
    
    • UIAlertController+Window.h.m
    #import "UIAlertController+Window.h"
    #import <objc/runtime.h>
    
    @interface UIAlertController (Private)
    
    @property (nonatomic, strong) UIWindow *alertWindow;
    
    @end
    
    @implementation UIAlertController (Private)
    
    @dynamic alertWindow;
    
    - (void)setAlertWindow:(UIWindow *)alertWindow {
        objc_setAssociatedObject(self, @selector(alertWindow), alertWindow, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    - (UIWindow *)alertWindow {
        return objc_getAssociatedObject(self, @selector(alertWindow));
    }
    
    @end
    
    @implementation UIAlertController (Window)
    
    - (void)show {
        [self show:YES];
    }
    
    - (void)show:(BOOL)animated {
        self.alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        self.alertWindow.rootViewController = [[UIViewController alloc] init];
        
        id<UIApplicationDelegate> delegate = [UIApplication sharedApplication].delegate;
        // Applications that does not load with UIMainStoryboardFile might not have a window property:
        if ([delegate respondsToSelector:@selector(window)]) {
            // we inherit the main window's tintColor
            self.alertWindow.tintColor = delegate.window.tintColor;
        }
        
        // window level is above the top window (this makes the alert, if it's a sheet, show over the keyboard)
        UIWindow *topWindow = [UIApplication sharedApplication].windows.lastObject;
        self.alertWindow.windowLevel = topWindow.windowLevel + 1;
        
        [self.alertWindow makeKeyAndVisible];
        [self.alertWindow.rootViewController presentViewController:self animated:animated completion:nil];
    }
    
    - (void)viewDidDisappear:(BOOL)animated {
        [super viewDidDisappear:animated];
        
        // precaution to insure window gets destroyed
        self.alertWindow.hidden = YES;
        self.alertWindow = nil;
    }
    
    @end
    
    • 使用实例
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"TITLE" message:@"test alert message" preferredStyle:UIAlertControllerStyleAlert];
        
        //add cancel button;
    [alertController addAction:[UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
    }]];
    
    [alertController show];
    

    相关文章

      网友评论

        本文标题:iOS-在任意当前画面弹出Alert

        本文链接:https://www.haomeiwen.com/subject/rvclxctx.html