【问题标题】:Image not showing up in ImageView after using Image Picker使用 Image Picker 后图像未显示在 ImageView 中
【发布时间】: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)
    }

}

【问题讨论】:

  • 复制粘贴代码时要小心。

标签: ios swift imageview imagepicker


【解决方案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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多