所选图像不会更改以前显示的图像

时间:2019-10-25 07:57:05

标签: swift xcode image

我有一个简单的设置,可以从相机或照片库中选择图像。当我选择新照片时,它与应用程序加载时的原始照片没有变化。

我认为这与代码的层次结构有关(不确定我是否使用正确的术语)。我将代码读取为所选图像,然后将变量“ originalImage”设置为所选图像。所以应该显示正确吗?好吧,剧透,我错了。

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    var originalImage = UIImage(named: "crossSection2.jpg")!

    @IBOutlet weak var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        imageView.image = originalImage
    }
    @IBAction func onCameraClicked(_ sender: Any) {
        let ac = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
        ac.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action) in
            self.showPicker(sourceType: .camera)
        }))
        ac.addAction(UIAlertAction(title: "Library", style: .default, handler: { (action) in
            self.showPicker(sourceType: .photoLibrary)
            }))
        ac.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
        self.present(ac, animated: true, completion: nil)
    }

    func showPicker(sourceType: UIImagePickerController.SourceType) {
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.sourceType = sourceType
        self.present(picker, animated: true, completion: nil) 
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage newImage : UIImage, editingInfo: [String : AnyObject]?) {
        dismiss(animated: true, completion: nil)
        self.originalImage = newImage
        self.imageView.image = newImage
    }
}

2 个答案:

答案 0 :(得分:0)

您需要更新UIImageView,而不仅仅是“ originalImage”。试试:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage newImage : UIImage, editingInfo: [String : AnyObject]?) {
    dismiss(animated: true, completion: nil)
    self.originalImage = newImage
    self.imageView.image = newImage
}

答案 1 :(得分:0)

来自https://developer.apple.com/documentation/uikit/uiimagepickercontrollerdelegate/1619152-imagepickercontroller

  

不建议使用imagePickerController:didFinishPickingMediaWithInfo:   代替。

因此,请尝试将代码更改为:

  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
         dismiss(animated: true, completion: nil)
        self.originalImage = info[.originalImage] as! UIImage
        self.imageView.image = (info[.originalImage] as! UIImage)
    }