or: “How I learned about the default value of userInteractionEnabled on UIImageViews”…

So, today I set out to create an iPad app in which my four year old son can drag some cookies around and get to do some light math.

In order to have draggable cookies, I figured the way to go would be to derive a DraggableImageView off of UIImageView that would add to itself a UIPanGestureRecognizer that would make the cookies (or any image, really) draggable.

This was my first attempt:

but for some reason I could not get it to recognize my dragging gestures! So I messed around with the code, coding various (failed) attempts at adding UIButtons and whatnot to my DraggableImageView in order to be able to do at least one single successful addTarget, but I simply could not make it work!

I loaded up some other Swift projects where my buttons worked fine, went back to the failing DraggableImageView, messed around with platform settings and other good stuff, suspecting that it was due to a bug – it is called XCode Beta, after all – and then it hit me:

  • New image view objects are configured to disregard user events by default. If you want to handle events in a custom subclass of UIImageView, you must explicitly change the value of the userInteractionEnabled property to YES after initializing the object.”
    Source: UIImageView documentation, emphasis mine.

Right! So I went and added self.userInteractionEnabled = true in the middle, which resulted in the full code reading (with nifty hover shadow effect added)

which in turn gave me these delicious draggable cookies…. Yummy!

cookies

How to create a draggable cookie with Swift

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: