使用 Image Picker 后图像未显示在 ImageView 中

Posted

技术标签:

【中文标题】使用 Image Picker 后图像未显示在 ImageView 中【英文标题】:Image not showing up in ImageView after using Image Picker 【发布时间】:2020-09-29 10:21:00 【问题描述】:

我正在尝试编写一个简单的应用程序,该应用程序将使用我的照片库中的照片更新 ImageView。我可以打开照片库并选择一张照片,但是这样做之后 ImageViewer 中的默认图像不会显示。知道为什么吗?

import UIKit

class ViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate 


    override func viewDidLoad() 
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    

    @IBOutlet weak var photoView: UIImageView!
    @IBAction func testGesture(_ sender: UITapGestureRecognizer) 

       let imagePickerController = UIImagePickerController()
        imagePickerController.sourceType = .photoLibrary
        imagePickerController.delegate = self
        present(imagePickerController, animated: true, completion: nil)
    

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) 
        dismiss(animated: true, completion: nil)

    

    private func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) 

        guard let selectedImage = info[UIImagePickerController.InfoKey.originalImage.rawValue] as? UIImage else 
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        

        photoView.image = selectedImage
        dismiss(animated: true, completion: nil)
    


【问题讨论】:

复制粘贴代码时要小心。 【参考方案1】:

您没有使用UIImagePickerControllerDelegatedidFinishPickingMediaWithInfo 方法。删除private 并将didFinishPickingMediaWithInfo 方法修改为UIImagePickerControllerDelegate 方法语法,就可以开始了。

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

    guard let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else 
        fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
    

    photoView.image = selectedImage
    print(selectedImage)
    dismiss(animated: true, completion: nil)

【讨论】:

以上是关于使用 Image Picker 后图像未显示在 ImageView 中的主要内容,如果未能解决你的问题,请参考以下文章

React-native node.js 显示错误:多部分:使用 react-native-image-picker 上传图像时未找到边界

在 Flutter 中使用 Multi Image Picker 选择图像后如何获取图像路径?

使用 multi_image_picker http 上传图片

如何在Flutter中保存图像文件?使用Image_picker插件选择文件

在颤振应用程序中添加 image_picker 插件后,Gradle Build 失败

React Native Image Picker 无法读取未定义的属性“showImagePicker”