我正在尝试创建代码,以便用户可以从其媒体库或“相机胶卷”中设置图像,并将其设置为屏幕上的ImageView。
我尝试添加此功能,但似乎不起作用
private func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true, completion: nil)
//You will get cropped image here..
if let image = info[editedImage] as UIImage
{
self.Picture.image = image
}
}
这是我现在的代码
class NewViewController: UIViewController, UIImagePickerControllerDelegate {
@IBOutlet var Picture: UIImageView! //the image I am trying to change
let imagepicker = UIImagePickerController()
@IBAction func ImagePicker(_ sender: Any) {
let alert = UIAlertController(title: "Photo", message: "Would you like to choose a picture from your libray, or take a new photo?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { action in
switch action.style{
case .default:
self.imagepicker.sourceType = .photoLibrary
self.imagepicker.allowsEditing = true
self.imagepicker.delegate = self
self.present(self.imagepicker, animated: true)
print("default")
case .cancel:
print("cancel")
case .destructive:
print("destructive")
}}))
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { action in
switch action.style{
case .default:
self.imagepicker.sourceType = .camera
self.imagepicker.allowsEditing = true
self.imagepicker.delegate = self
self.present(self.imagepicker, animated: true)
print("default")
case .cancel:
print("cancel")
case .destructive:
print("destructive")
}}))
self.present(alert, animated: true, completion: nil)
}
}
答案 0 :(得分:0)
您为什么在这里尝试使用editedImage
作为密钥?应该是.editedImage
答案 1 :(得分:0)
您需要将method
签名更改为
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true, completion: nil)
guard let image = info[.editedImage] as? UIImage else { return }
self.Picture.image = image
}
您可以检查方法签名here。当前,由于参数错误,UIImagePickerController
委托不会调用您拥有的方法。如果您从方法中删除private
关键字,则会收到以下警告,这表示它看起来像是相同的方法,但不是
UIImagePickerController
代表将呼叫。
实例方法 几乎'imagePickerController(:didFinishPickingMediaWithInfo :)' 符合可选要求 协议的“ imagePickerController(:didFinishPickingMediaWithInfo :)” 'UIImagePickerControllerDelegate'