Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a UIView as a button

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.

like image 593
Jon Cox Avatar asked Oct 09 '22 11:10

Jon Cox


2 Answers

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

like image 187
fbernardo Avatar answered Oct 12 '22 10:10

fbernardo


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.

like image 28
Dylan Vander Berg Avatar answered Oct 12 '22 09:10

Dylan Vander Berg