问题描述
我使用WKWebView。
“警告”对话框在iPhone上正常工作,但在iPad上不可见。我该如何解决?
func webView(_ webView: WKWebView,runJavaScriptAlertPanelWithMessage message: String,initiatedByFrame frame: WKFrameInfo,completionHandler: @escaping () -> Void) {
let alertController = UIAlertController(title: nil,message: message,preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "Ok",style: .default,handler: { (action) in
completionHandler()
}))
if UIDevice.current.userInterfaceIdiom == .pad {
if let popoverPresentationController = alertController.popoverPresentationController {
popoverPresentationController.sourceView = self.view
popoverPresentationController.sourceRect = CGRect(x: self.view.bounds.midX,y: self.view.bounds.midY,width: 0,height: 0)
popoverPresentationController.permittedArrowDirections = []
}
} else {
self.present(alertController,animated: true,completion: nil)
}
}
解决方法
如果是iPad,则不会在if-let内部显示ViewController。
将self.present(alertController,animated: true,completion: nil)
移动到else块之外。
if UIDevice.current.userInterfaceIdiom == .pad {
if let popoverPresentationController = alertController.popoverPresentationController {
popoverPresentationController.sourceView = self.view
popoverPresentationController.sourceRect = CGRect(x: self.view.bounds.midX,y: self.view.bounds.midY,width: 0,height: 0)
popoverPresentationController.permittedArrowDirections = []
}
}
self.present(alertController,completion: nil)
作为旁注,请检查alertController.popoverPresentationController是否不为空