Show UIAlertController over keyboard

前端 未结 4 1291
不知归路
不知归路 2020-12-25 14:48

In iOS 8 and lower show a UIActionSheet when keyboard is presented will present the action sheet over the keyboard. With iOS 9 this is no longer the case.

4条回答
  •  悲&欢浪女
    2020-12-25 15:21

    Based on Leo Natan's answer, I've created a Swift extension for presenting an alert sheet over the keyboard.

    In my brief testing, the alertWindow is deallocated after the alert is dismissed, I believe because there's no strong reference to it outside of the alert. This means there's no need to hide or deallocate it in your UIAlertActions.

    extension UIAlertController {
    
        func presentOverKeyboard(animated: Bool, completion: (() -> Void)?) {
    
            let alertWindow = UIWindow(frame: UIScreen.mainScreen().bounds)
    
            // If you need a white/hidden/other status bar, use an appropriate VC.
            // You may not need a custom class, and you can just use UIViewController()
            alertWindow.rootViewController = whiteStatusBarVC()
    
            alertWindow.windowLevel = 10000001
            alertWindow.hidden = false
    
            // Set to a tint if you'd like
            alertWindow.tintColor = UIColor.greenColor()
    
            alertWindow.rootViewController?.presentViewController(self, animated: animated, completion: completion)
        }
    }
    
    private class whiteStatusBarVC: UIViewController {
        private override func preferredStatusBarStyle() -> UIStatusBarStyle {
            return .LightContent
        }
    }
    

提交回复
热议问题