1

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

}
4

1 回答 1

2

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

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)
}
于 2020-06-10T05:04:04.197 回答