我正在尝试创建代码,以便用户可以从其库或相机胶卷中设置图像,并将其设置为屏幕上的 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)
}
}
最佳答案
您需要将方法
签名更改为,
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
委托(delegate)未调用您拥有的方法。如果您从方法中删除 private
关键字,您将收到如下警告,这意味着它看起来像相同的方法,但事实并非如此
UIImagePickerController
委托(delegate)将调用。
Instance method 'imagePickerController(:didFinishPickingMediaWithInfo:)' nearly matches optional requirement 'imagePickerController(:didFinishPickingMediaWithInfo:)' of protocol 'UIImagePickerControllerDelegate'
关于ios - 在 Swift 中将拾取的图像从 UIImagePicker 设置为 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56268815/