在 Swift 中将从 UIImagePicker 选取的图像设置为 UIImageView

Setting picked image from UIImagePicker to UIImageView in Swift

我正在尝试创建代码,以便用户可以从他们的库或从他们的相机胶卷中设置图像,并将其设置为屏幕上的 ImageView。

我尝试添加这个功能,但是它似乎不起作用

private func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        picker.dismiss(animated: true, completion: nil)
        //You will get cropped image here..
        if let image = info[editedImage] as UIImage
        {
            self.Picture.image = image
        }
    }

这是我目前的代码

class NewViewController: UIViewController, UIImagePickerControllerDelegate {

    @IBOutlet var Picture: UIImageView! //the image I am trying to change 

    let imagepicker = UIImagePickerController()

@IBAction func ImagePicker(_ sender: Any) {
        let alert = UIAlertController(title: "Photo", message: "Would you like to choose a picture from your libray, or take a new photo?", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { action in
            switch action.style{
            case .default:
                self.imagepicker.sourceType = .photoLibrary
                self.imagepicker.allowsEditing = true
                self.imagepicker.delegate = self
                self.present(self.imagepicker, animated: true)
                print("default")

            case .cancel:
                print("cancel")

            case .destructive:
                print("destructive")
            }}))
        alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { action in
            switch action.style{
            case .default:
                self.imagepicker.sourceType = .camera
                self.imagepicker.allowsEditing = true
                self.imagepicker.delegate = self
                self.present(self.imagepicker, animated: true)

                print("default")

            case .cancel:
                print("cancel")

            case .destructive:
                print("destructive")
            }}))
        self.present(alert, animated: true, completion: nil)
    }
}

为什么要在这里使用 editedImage 作为键?应该是.editedImage

您需要将 method 签名更改为,

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    picker.dismiss(animated: true, completion: nil)
    guard let image = info[.editedImage] as? UIImage else { return }
    self.Picture.image = image
} 

您可以检查方法签名here。当前,由于参数错误,UIImagePickerController 委托未调用您拥有的方法。如果从方法中删除 private 关键字,您将收到如下警告,这意味着它看起来像相同的方法,但不是 UIImagePickerController代表将打电话。

Instance method 'imagePickerController(:didFinishPickingMediaWithInfo:)' nearly matches optional requirement 'imagePickerController(:didFinishPickingMediaWithInfo:)' of protocol 'UIImagePickerControllerDelegate'