快速从图库中选择照片不起作用

时间:2018-08-30 19:58:16

标签: swift uiimage uiimagepickercontroller

在我的应用中,我有一个“ addImgBtn”,应允许用户从其照片中选择图像。我也有存储一些临时图像的“ profileImg”。

当我单击“ addImg”按钮时,它会显示所有照片,但是当我单击“选择”时,它不会将临时图像替换为所选的临时图像,这是我的代码:

class myClass: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

@IBOutlet weak var profileImg: UIImageView!
@IBOutlet weak var addImgBtn: UIButton!

@IBAction func addImgBtn(_ sender: Any) {
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
        imagePicker.allowsEditing = true
        self.present(imagePicker, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){
    self.dismiss(animated: true, completion: { () -> Void in

    })

    profileImg.image = image
 }
}

1 个答案:

答案 0 :(得分:1)

您使用了错误的imagePickerController方法,请更改为以下内容:

 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    self.dismiss(animated: true, completion: { () -> Void in
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
            self.profileImg.image = image
        }
    })
}

这应该有效!作为一般提示,请命令单击UIImagePickerControllerDelegate或您正在xcode中实现的任何委托,它将告诉您所有可用的方法,等等。