6

I'm trying to use a UIView I've created in Storyboard as a button. I assumed it would be possible to use a UIButton, setting the type to custom. However I was unable to add subviews to a custom UIButton in Storyboard.

As such I've just spent the last hour reinventing the wheel by making my own custom gesture recoginizers to reimplement button functionality.

Surely this isn't the best way of doing it though, so my question - to more experienced iOS developers than myself - is what is the best way to make a custom button?

To be clear it needs to:

  • Use the UIView I've created as it's hittable area.
  • Be able to show a different state depending on whether is currently highlighted or not (i.e. touch down).
  • Perform some action when actually tapped.

Thank you for your help.

Jon Cox
  • 10,622
  • 22
  • 78
  • 123

4 Answers4

3

You can use a UIButton, set the type to custom, and then programmatically add your subviews...

fbernardo
  • 10,016
  • 3
  • 33
  • 46
  • So to have a custom button I'd essentially have to make everything programmatically rather than using Storyboard? – Jon Cox Mar 07 '12 at 23:55
  • Nop, you create it on storyboard and then you add your views (from interface builder for example) programmatically. – fbernardo Mar 07 '12 at 23:56
2

Change your UIView into a UIControl in the storyboard. Then use the method
[controlViewName addTarget:self action:@selector(*click handler method*) forControlEvents:UIControlEventTouchDown];. click handler method is a placeholder for the method name of your handler. Use this method except change out the UIControlEventTouchDown for UIControlEventTouchInside and UIControlEventTouchDragExit to call a method when the user finishes their click and drags their finger out of the view respectively. I used this for something I'm working on now and it works great.

In Touch down you will want to: highlight all subviews
In Touch up inside you will want to: unhighlight all subviews and perform segue or do whatever the button is supposed to do
In Touch Drag Exit you will want to: unhighlight all subviews

See second answer by LiCheng in this similiar SO post.

Community
  • 1
  • 1
Dylan Vander Berg
  • 1,809
  • 1
  • 22
  • 37
0

Subclass UIControl instead. You can add subviews to it and it can respond to actions

stephenmuss
  • 2,445
  • 2
  • 20
  • 29
0

Why are you implementing your own GestureRecognizer? I recommend using the UIView so you can add subviews in the interface builder and adding a UITapGestureRecognizer. You can even do this graphically since you don't care about IOS4 support.

Alexander Theißen
  • 3,799
  • 4
  • 28
  • 35
  • 1
    The problem I had with using a UITapGestureRecognizer was that it doesn't offer any way to highlight the UIView on touch down. Otherwise it would have been perfect (and considerably simpler than any other solution). – Jon Cox Mar 08 '12 at 00:03