ios 如何使用Swift使UIAlertController与iPad和iPhone兼容

yqyhoc1h  于 2022-12-27  发布在  iOS
关注(0)|答案(3)|浏览(195)

我创建了一个图像选择器UI,用户点击按钮时,我想在其中进行选择,我使用UIAlertController完成了这一操作,当我在iPhone中测试时,它工作正常,但当我在iPad中测试时,点击按钮后,应用程序崩溃。
如何使UIAlertController也兼容iPad?

kgsdhlau

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)
tvokkenx

tvokkenx2#

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

6tqwzwtp

6tqwzwtp3#

我们可以用

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)

}
    • 上述代码中使用的函数(适用于照相机和多媒体资料)**
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)
}

相关问题