wallacer
wallacer

Reputation: 13213

Open a UIImagePicker from a UIImageView

I am writing a simple app where I have a UIImageView that when clicked on, should open a UIImagePickerController, and once an image is selected, is should just assign that image to the UIImageView

I started by sub-classing UIImageView, and giving it a touchesBegan which would open an ImagePicker.

My question is, since only a UIViewController can call presentModalViewController to show the imagePicker, how should I go about this?

It's bad design to have your a view reference it's controller (though I guess my imageview is a subview). So I don't know how I'd pass the message up to the controller.

The other option is to detect touches in the controller to begin with, but then the only way I can see to tell if the touch was on the imageview is to actually test if the touch is within the frame of the imageview. This approach seems clunky to me... Am I missing something obvious?

Any thoughts on which method to go with, or any suggestions on a better method would be much appreciated! Thanks!

Upvotes: 1

Views: 272

Answers (3)

pheelicks
pheelicks

Reputation: 7469

The Objective C way of doing this is to declare a custom delegate that your view controller implements. So for your case, it would a have a single method, something like viewTapped. Have your custom class call this delegate method whenever it is clicked.

Then make your view controller implement this delegate and launch the modal view controller when the delegate method is called.

Upvotes: 0

Kal
Kal

Reputation: 24910

When you init the UIImageView subclass, pass a reference to the view controller that loads the image view.

Then, your touchup inside on the UIImageView can call presentModalViewController with that view controller.

Upvotes: 0

PengOne
PengOne

Reputation: 48398

You don't necessarily need to subclass UIImageView to do this. You can have it as a subview of your main UIView for some UIViewController, and add a UIGestureRecognizer to the UIImageView. Then the method that tapping or swiping the UIImageView triggers will be in your UIViewController, so you can easily present a modal view from there.

Upvotes: 1

Related Questions