【发布时间】:2019-04-11 12:33:14
【问题描述】:
我想从库中获取图像,但是直到我从库中选择图像才会显示
这是我的代码
@IBAction func btnProfile(_ sender: UIButton) {
let alert = UIAlertController(title: "Change Profil Image", message: "Pilih Foto", preferredStyle: UIAlertControllerStyle.actionSheet)
alert.addAction(UIAlertAction(title: "Gunakan Kamera", style: .default, handler: { (action: UIAlertAction!) in
print("Gunakan Kamera")
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
}))
alert.addAction(UIAlertAction(title: "Ambil Foto dari Galery", style: .default, handler: { (action: UIAlertAction!) in
print("Ambil Foto dari Galery")
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary;
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Cancel")
}))
present(alert, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let image = info[.originalImage] as? UIImage else { return } // error in here >> 'UIImage?' is not convertible to 'UIImage' >> and warning yellow >> Cast from 'Slice<Dictionary<UIImagePickerController.InfoKey, Any>>' (aka 'Slice<Dictionary<NSString, Any>>') to unrelated type 'UIImage' always fails
picker.dismiss(animated: true, completion: nil)
imgProf.image = image
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
我想在 UIimageview 上显示图像,但是从库中检索它后它并不总是出现, 保护让图像出错,并在那里警告黄色 我用的是 swift 3
这是 UIImagePickerControllerDelegate
public protocol UIImagePickerControllerDelegate : NSObjectProtocol {
@available(iOS 2.0, *)
optional public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
@available(iOS 2.0, *)
optional public func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
}
【问题讨论】:
-
@Kamran,我已经更新了
-
所以您使用的是 Swift 4.2? Xcode 版本是多少?
-
swift 4,但我使用的是 xcode 10.0 版
-
为此您可以尝试
info[UIImagePickerController.InfoKey.originalImage.rawValue]而不是info[.originalImage] -
我又出错了 >> 类型 'UIImagePickerController.InfoKey' (aka 'NSString') 没有成员 'originalImage'
标签: swift swift3 uiimageview uiimagepickercontroller