问题
I have a view that contains several images, each intended to be selected from the device's photo library.
I followed an example from the Food Tracker tutorial, using Tap Gesture Recognizers, one for each image view.
I've wired an outlet for each UIImageView into my view controller.
When an image is selected, I want the image from the device's photo library to be set to the image property of the selected UIImageView. The way I thought to do this is to use closures encapsulated into a class adopting the UIImagePickerControllerDelegate protocol. However, the methods on this class are never called. If I instead make my view controller the delegate, the methods are correctly called (but I don't know which image to set).
Here's some code to clarify:
// Encapsulate callbacks for the selected image
class ImagePicker: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var select: (image: UIImage) -> Void
var cancel: () -> Void
init(select: (image: UIImage) -> Void, cancel: () -> Void) {
self.select = select
self.cancel = cancel
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
cancel()
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
select(selectedImage)
}
}
Then within my view controller, I have wired this method to the gesture recognizer:
@IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
textField.resignFirstResponder()
let imagePickerController = UIImagePickerController()
imagePickerController.sourceType = .PhotoLibrary
let imagePicker = ImagePicker(
select: {(image: UIImage) -> Void in
let imageView = sender.view as! UIImageView
imageView.image = image
self.dismissViewControllerAnimated(true, completion: nil)
},
cancel: {() -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}
)
imagePickerController.delegate = imagePicker
presentViewController(imagePickerController, animated: true, completion: nil)
}
The methods are never called. I've set break points (and printed to the console) in both the closures and in the two delegate methods (imagePickerControllerDidCancel(_:)
and imagePickerController(_:didFinishPickingMediaWithInfo:)
).
Is there something else I need to implement? Or is this just "the wrong way to do it"? Thanks for any help.
回答1:
Your ImagePicker
instance goes out of scope at the end of the selectImageFromPhotoLibrary
function. Therefore the image picker's delegate is gone. You need to keep a strong reference to the ImagePicker
. Using an instance variable is a likely option.
来源:https://stackoverflow.com/questions/33270586/uiimagepickercontrollerdelegate-methods-not-called-when-delegate-not-uiviewcontr