【发布时间】:2020-06-30 22:02:58
【问题描述】:
我从零开始开发 iOS 应用程序,但我需要创建一个可以使用 iPhone 相机拍摄图像的应用程序。我找到了 UIImagePickerController 但我无法弄清楚如何正确实现它。如果有人可以帮助我,那就太好了。此外,我对应用程序开发知之甚少,因此如果有任何背景知识,我将不胜感激。
【问题讨论】:
我从零开始开发 iOS 应用程序,但我需要创建一个可以使用 iPhone 相机拍摄图像的应用程序。我找到了 UIImagePickerController 但我无法弄清楚如何正确实现它。如果有人可以帮助我,那就太好了。此外,我对应用程序开发知之甚少,因此如果有任何背景知识,我将不胜感激。
【问题讨论】:
你可以在任何你想打开 UIImagePickerController 的地方调用这个方法:
func openImagePicker() {
let vc = UIImagePickerController()
vc.sourceType = .camera
vc.allowsEditing = true
vc.delegate = self
present(vc, animated: true)
}
通过制作这样的扩展,使您的视图控制器同时符合 UINavigationControllerDelegate 和 UIImagePickerControllerDelegate:
extension youViewControllerClass: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true) // dismisses camera controller
guard let image = info[.editedImage] as? UIImage else {
print("No image found")
return
}
// You will get your image here
print(image.size)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
picker.dismiss(animated: true, completion: nil)
// here you will get the cancel event
}
}
【讨论】:
vc.delegate = self 和 present(vc, animated: true) 行出现错误。这两个错误都表明我正在使用未解析的标识符来表示自己和存在。我在extension youViewControllerClass:... 行也收到错误消息。此错误表示我正在使用未声明的类型。有什么办法可以解决这个问题?
present(vc, animated: true) 是 UIViewController 及其子类的属性。您还需要将 youViewControllerClass 替换为您的 UIViewController 的原始名称。