我试图了解有关委托模式的更多信息。我编写了一个访问用户相机胶卷的应用程序,我希望在用户选择图像后在视图控制器上显示该图像。以下是我到目前为止的情况:
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imagePickerView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
// Delegate Methods
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
imagePickerView.image = image
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func pickAnImage(_ sender: Any) {
let pickerController = UIImagePickerController()
present(pickerController, animated: true, completion: nil)
}
}
相机胶卷按预期显示,取消按钮关闭模式。选择图像也会取消模式,但该图像不会显示在屏幕上。我已确认我的imagePickerController
已被更正为引用。我错过了什么?
答案 0 :(得分:7)
选择图像后,您必须关闭控制器,可能以下详细功能可以帮助您。
对于Swift 4.2:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
var selectedImageFromPicker: UIImage?
if let editedImage = info[.editedImage] as? UIImage {
selectedImageFromPicker = editedImage
} else if let originalImage = info[.originalImage] as? UIImage {
selectedImageFromPicker = originalImage
}
if let selectedImage = selectedImageFromPicker {
imageView.image = selectedImage
}
dismiss(animated: true, completion: nil)
}
在Swift 4.2之前:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var selectedImageFromPicker: UIImage?
if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
selectedImageFromPicker = editedImage
} else if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
selectedImageFromPicker = originalImage
}
if let selectedImage = selectedImageFromPicker {
imageView.image = selectedImage
}
dismiss(animated: true, completion: nil)
}
由于我从这个答案中收到了很多分数,因此我添加了一个更简洁的答案(将图像设置为imageView只需要一行)。
奖金回答:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
imageView.image = (info[.editedImage] ?? info[.originalImage]) as? UIImage
dismiss(animated: true)
}
答案 1 :(得分:1)
您需要将视图控制器设置为pickerController的委托
// pickerController.delegate = self
同时检查imagePickerView插座是否已连接。
答案 2 :(得分:0)
UIImagePickerControllerEditedImage
其他UIImagePickerControllerOriginalImage
)