Swift 5 UIImagePickerController 未被调用

Swift 5 UIImagePickerController is not getting called

我最多standard/out个在UIImagePicker中调用delegate函数的盒子代码:

导入基金会 导入 UIKit //导入UIKit.UIImage

class FirstViewController:
      UIViewController
    , UIImagePickerControllerDelegate
{

    let imagePicker = UIImagePickerController()
    @IBOutlet weak var bigImageView: UIImageView!

    var newlyPickedImage: UIImage?

    override func viewDidLoad() {

        super.viewDidLoad()
        self.view.backgroundColor = Color.offWhiteLight

        let singleTap = UITapGestureRecognizer(target: self, action: #selector(onTapImageView))
        self.view.isUserInteractionEnabled = true
        self.view.addGestureRecognizer(singleTap)
    }

    @objc func onTapImageView(){
        DispatchQueue.main.async {
            self.imagePicker.allowsEditing = true
            self.imagePicker.sourceType = .photoLibrary
            self.present(self.imagePicker, animated: true, completion: nil)
        }
    }

    func imagePickerController(
         _ picker: UIImagePickerController
        , didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
    {
        print("assert enter function") /// not entered

        if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            self.bigImageView.image = pickedImage
            print("picked image: \(pickedImage)")
        }

        dismiss(animated: true, completion: nil)
    }
}

问题是 func imagePickerController 没有被调用。这很奇怪,因为在不同的视图中,确切的代码确实调用了 func imagePickerController。我还尝试在 Appdelegate 中实例化一个全局 UIImagePickerController 实例并引用它,但仍未调用该调用。

您似乎缺少 UIImagePickerController 的设置委托。将您的 onTapImageView 替换为:

@objc func onTapImageView(){
    DispatchQueue.main.async {
        self.imagePicker.allowsEditing = true
        self.imagePicker.sourceType = .photoLibrary
        self.imagePicker.delegate = self
        self.present(self.imagePicker, animated: true, completion: nil)
    }
}

此外,您还需要控制器确认 UINavigationControllerDelegate,因此向 FirstViewController 添加一致性,如下所示:

class FirstViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {