Project Jo

UIAlertController 를 여러번 띄우기 본문

Developer/iOS

UIAlertController 를 여러번 띄우기

Project Jo 2020. 8. 20. 20:00

UIAlertController 를 사용하게 되면서 UIAlertView 와는 다르게 어러개의 팝업이 중첩되어 표시되지 않는 상황을 확인하였다.

 

따라서 윈도우 1개에 UIAlertController 1개를 표시하여 여러개의 UIAlertController 를 표시가 가능하게 하는 방법이 좋아보여 정리하였다.

 

단, 해당 방법은 윈도우에 추가 하기 때문에 최근에 나온 Scene 을 이용하는 앱에는 사용이 불가능하다.

 

ObObjective c

- (void)showAlert
{
    __block UIWindow *alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    alertWindow.rootViewController = [[UIViewController alloc] init];
    alertWindow.windowLevel = UIWindowLevelAlert + 1;
    
    [alertWindow makeKeyAndVisible];
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"UIAlertController"
                                                                   message:@"UIAlertController Multi Show"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* onAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                     handler:^(UIAlertAction * action) {
        [alertWindow setHidden:YES];
    }];
    
    [alert addAction:onAction];
    [alertWindow.rootViewController presentViewController:alert animated:YES completion:nil];
}

Alert ObObjective c.zip
0.04MB

 

Swift

    func showAlert() {
        
        var alertWindow: UIWindow?
        
        let windowScene = UIApplication.shared
            .connectedScenes
            .filter { $0.activationState == .foregroundActive }
            .first
        
        if let windowScene = windowScene as? UIWindowScene {
            alertWindow = UIWindow(windowScene: windowScene)
        } else {
            alertWindow = UIWindow.init(frame: UIScreen.main.bounds)
        }
        
        alertWindow?.frame = UIScreen.main.bounds
        alertWindow?.rootViewController = UIViewController.init()
        alertWindow?.windowLevel = UIWindow.Level.alert + 1
        
        alertWindow?.makeKeyAndVisible()
        
        let alert: UIAlertController = UIAlertController.init(title: "UIAlertController",
                                                              message: "UIAlertController Multi Show",
            preferredStyle: .alert)
        
        let onAction: UIAlertAction = UIAlertAction.init(title: "OK",
                                                         style: .default) { (action: UIAlertAction) in
                                                            alertWindow?.isHidden = true
        }
        
        alert.addAction(onAction)
        alertWindow?.rootViewController?.present(alert, animated: true, completion: nil)
    }

Alert Swift.zip
0.03MB