I'm very new to Xcode and Swift, and I was trying to display an image in a UIImageView
that was selected using UIImagePickerController
. I linked the UIImageView
using an @IBOutlet
and I put some if
statements at the bottom to allow for editing of the selected picture, but I got stuck when an error popped up in my code. I'm pretty sure that the problem has something to do with how I am referencing the UIImageView
, but I don't know how to do it in a different way. I just got this account to ask this question, so forgive me for the way I made this post.
Here is the code:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func openPhotosButton(_ sender: UIButton) {
showImagePickerController()
}
@IBOutlet weak var characterView: UIImageView!
}
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func showImagePickerController() {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
imagePickerController.sourceType = .photoLibrary
present(imagePickerController, animated: true)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let editedImage = info[UIImagePickerController.InfoKey.editedImage] as UIImage {
characterView.image = editedImage
}
else if let originalImage = info[UIImagePickerController.InfoKey.originalImage] as UIImage {
characterView.image = originalImage
}
dismiss(animated: true)
}
}
Picture from Xcode: