我创建了一个图像选择器UI,用户点击按钮时,我想在其中进行选择,我使用UIAlertController完成了这一操作,当我在iPhone中测试时,它工作正常,但当我在iPad中测试时,点击按钮后,应用程序崩溃。如何使UIAlertController也兼容iPad?
kgsdhlau1#
UIView控制器的扩展
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)
tvokkenx2#
在iPad上,uialertcontroller必须相对于其他控制器显示,因为你不能只在“屏幕上的任何地方”显示它。
6tqwzwtp3#
我们可以用
let ac = UIAlertController(title: nil, message: nil, preferredStyle: UIDevice.current.userInterfaceIdiom == .pad ? .alert : .actionSheet)
@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) }
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) }
3条答案
按热度按时间kgsdhlau1#
UIView控制器的扩展
用法
tvokkenx2#
在iPad上,uialertcontroller必须相对于其他控制器显示,因为你不能只在“屏幕上的任何地方”显示它。
6tqwzwtp3#
我们可以用