我正在尝试编写一个简单的应用程序,用我的照片库中的照片更新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)
}
}
最佳答案
您没有使用UIImagePickerControllerDelegate
的didFinishPickingMediaWithInfo
方法。删除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/