Swift 提示框(keyWindow)
近日在学习Swift的过程中用到了提示框,按照原来OC的方法在keyWindow上推出提示框的时候,被提示
'keyWindow' was deprecated in iOS 13.0: Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes
iOS13以后原来的keyWindow方法就不能使用了,那么我们应该怎么获取keyWindow呢?
1.解决方法
方法一:
UIApplication.shared.windows.filter {$0.isKeyWindow}.first
或者
UIApplication.shared.windows.first {$0.isKeyWindow}
方法二:
let keyWindow = UIApplication.shared.connectedScenes
.filter({$0.activationState == .foregroundActive})
.map({$0 as? UIWindowScene})
.compactMap({$0})
.first?.windows
.filter({$0.isKeyWindow}).first
2.另外附上自己封装的提示框,仅供参考
import Foundation
import UIKit
extension UIAlertController {
///在指定视图控制器上弹出普通消息提示框
static func showAlert(message: String, in viewController: UIViewController) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
viewController.present(alert, animated: true)
}
///在根视图控制器上弹出普通消息提示框
static func showAlert(message: String) {
let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
if let vc = keyWindow?.rootViewController {
showAlert(message: message, in: vc)
}
}
///在指定视图控制器上弹出确认框
static func showConfirm(message: String, in viewController: UIViewController, confirm:((UIAlertAction) -> Void)?) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "确定", style: .default, handler: confirm))
viewController.present(alert, animated: true)
}
///在根视图控制器上弹出确认框
static func showConfirm(message: String, confirm: ((UIAlertAction) -> Void)?) {
let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
if let vc = keyWindow?.rootViewController {
showConfirm(message: message, in: vc, confirm: confirm)
}
}
/// 在指定视图控制器上提示警告信息
static func showWarning(_ message: String, in viewController: UIViewController) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
viewController.present(alert, animated: true, completion: nil)
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
alert.dismiss(animated: true, completion: nil)
}
}
/// 在根定视图控制器上提示警告信息
static func showWarning(_ message: String) {
let keyWindow = UIApplication.shared.connectedScenes
.filter({$0.activationState == .foregroundActive})
.map({$0 as? UIWindowScene})
.compactMap({$0})
.first?.windows
.filter({$0.isKeyWindow}).first
if let vc = keyWindow?.rootViewController {
showWarning(message, in: vc)
}
}
}
网友评论