如何使用Swift使UIAlertController兼容iPad和iphone



我创建了一个图像选择器UI,我想在用户点击按钮时进行选择,我用UIAlertController做过当我在iPhone中测试它时它工作得很完美,当我在iPad上测试它时,点击按钮后,应用程序崩溃了。

我如何让UIAlertController也兼容iPad ?

UIViewController扩展

extension UIViewController{
public func addAlertForiPad(alert: UIAlertController) {
if let alertController = alert.popoverPresentationController {
alertController.sourceView = view
alertController.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
alertController.permittedArrowDirections = []
}
}
}

用法

let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .actionSheet)

if UIDevice.current.userInterfaceIdiom == .pad {
addAlertForiPad(alert: alertController)
}
alertController.popoverPresentationController?.sourceView = view
alertController.addAction(UIAlertAction(title: "Approve", style: .default , handler:{ (UIAlertAction)in
print("User click Approve button")
}))

alertController.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler:{ (UIAlertAction)in
print("User click Dismiss button")
}))

present(alertController, animated: true, completion: nil)

在iPad上,uialertcontroller必须相对于其他控制器显示,因为你不能在屏幕上的任何地方显示它。

我们可以使用

let ac = UIAlertController(title: nil, message: nil, preferredStyle: UIDevice.current.userInterfaceIdiom == .pad ? .alert : .actionSheet)

swift完整代码

@IBAction func pickBTN(_ sender: UIButton) {

let ac = UIAlertController(title: nil, message: nil, preferredStyle: UIDevice.current.userInterfaceIdiom == .pad ? .alert : .actionSheet)

ac.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { action in
self.gallery()
}))
ac.addAction(UIAlertAction(title: "Camera", style: .default, handler: { action in
self.camera()
}))
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { action in
}))

present(ac, animated: true)

}

以上代码中使用的函数(用于camera &画廊)

func gallery (){
imagePicker.allowsEditing = false
imagePicker.sourceType = .savedPhotosAlbum
present(imagePicker, animated: true, completion: nil)
}
func camera (){
imagePicker.allowsEditing = false
imagePicker.sourceType = .camera
present(imagePicker, animated: true, completion: nil)
}

最新更新