Swift 所选图像不会更改以前显示的图像
我有一个简单的设置,可以从相机或照片库中选择图像。当我选择一张新照片时,它不会改变应用程序加载的原始照片 我认为这和层次结构有关,不确定我是否用正确的代码术语使用了它。我将代码作为所选图像读取,然后将变量originalImage设置为所选图像。所以这应该是正确的吗?好吧,扰流板,我错了Swift 所选图像不会更改以前显示的图像,swift,xcode,image,Swift,Xcode,Image,我有一个简单的设置,可以从相机或照片库中选择图像。当我选择一张新照片时,它不会改变应用程序加载的原始照片 我认为这和层次结构有关,不确定我是否用正确的代码术语使用了它。我将代码作为所选图像读取,然后将变量originalImage设置为所选图像。所以这应该是正确的吗?好吧,扰流板,我错了 import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationContro
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
}
}
您需要更新UIImageView,而不仅仅是原始图像。尝试:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage newImage : UIImage, editingInfo: [String : AnyObject]?) {
dismiss(animated: true, completion: nil)
self.originalImage = newImage
self.imageView.image = newImage
}
从
不推荐使用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)
}
那是有道理的,不是吗。问了这个问题后,我碰巧试了一下,但还是不起作用。还有其他想法吗?好的,我以前没有注意到。控制台中出现布局约束错误。[LayoutConstraints]无法同时满足约束。可能下面列表中至少有一个约束是您不想要的。尝试以下方法:1查看每个约束条件,并尝试找出您不期望的约束条件;2找到添加了不需要的约束的代码并修复它。我取出约束,运行它,更新它,运行它,两者都不起作用。我不应该使用安全区域吗?我将所有四个约束都设置为0。不知道为什么我还是会犯这个错误。谢谢你,就是这样!非常感谢