ios - 使用图像选择器后,图像未显示在ImageView中

标签 ios swift imageview imagepicker

我正在尝试编写一个简单的应用程序,用我的照片库中的照片更新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)
    }

}

最佳答案

您没有使用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)
}

关于ios - 使用图像选择器后,图像未显示在ImageView中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62296167/

相关文章:

android - backgroundimage 隐藏了 android 应用程序中的所有按钮

android - 停止动画并重新开始

Android - Imageview 在所有屏幕分辨率的中心

ios - 所有 iOS 屏幕尺寸的启动屏幕图像尺寸

swift - 如何修复 Xcode ARKit 中类型 'SCNNode' 的值没有成员 'materials'

iphone - 将类非自动引用计数导入我的项目时出错

ios - 以编程方式分配接口(interface)对象会影响加载时间吗?

ios - 具有部分匹配值的 Firebase iOS 查询数据

ios - 创建从容器 View 到 View Controller 的引用(IBOutlet)

带有 healthkit 的 iOS 通用应用程序无法在 iPad 上运行