Iphone – n way to make an invisible UIButton that will still “be there” and catch touch events for the UIImageView

cocoa-touchiphoneuiimageviewuikit

I thought to be clever and just put an transparent UIButton over an UIImageView with the exact frame size, so that I can wire it up easily with any event I like, for example TouchUpInside, and make it call a action method of an view controller when the user touches it. Well, it works until alpha is below 0.1f. If I do 0.01f, it will not work. So to get it work, when looking a long time on the screen, you'll see that 0.1f of alpha shining through. And that's totally disgusting 😉

It seems like iPhone OS trys to be clever and won't catch events on the button if it's visually not there. Any idea how to solve that?

Sure I could make a subclass of UIImageView and implement touchesBegan:… etc., but it doesn't feel really elegant. I mean…when I want to hyperlink an image on the web, I would never want create my own HTML element for that image, just to wire it up to an url when it's clicked. That just doesn't make a lot of sense to me.

Best Answer

You should be able to set the button's 'Type' to Custom in Interface Builder, and it will not display any text or graphical elements over the UIImageView. This way, you don't need to adjust the alpha. If the view is built from code, use:

button = [UIButton buttonWithType:UIButtonTypeCustom];
Related Topic