9

I am creating a custom UIView. I am wondering how can I replicate the UIButton behavior on this UIView.

I would like to be able to call addTarget to it like an UIButton.

I know that I can subclass UIControl and call

self.sendActionsForControlEvents(UIControlEvents.TouchUpInside);

but I would like to do it on an UIView since I am designing it on a XIB file.

Bowdzone
  • 3,827
  • 11
  • 39
  • 52
JayVDiyk
  • 4,277
  • 22
  • 70
  • 135
  • Add UIControl with custom view bounds with Backgound color clear then add target that UIControl otherwise add TapGesture to the View – TamilKing Nov 02 '15 at 06:49

4 Answers4

16

There is an easy way to achieve this.

  1. Go to Interface builder of your class
  2. Select the view u want to add action
  3. open IDENTITY INSPECTOR, change class from UIView to 'UIControl'.

Now u can add any IBAction method to this view.

Its working like charm. happy coding. hope it may help

Update

its working in xCode 10.1 and swift 4+

Subhash Sharma
  • 745
  • 6
  • 24
  • 1
    this is brilliant and much nicer than the other solutions. it's easy to create a custom button this way, just as an example. This should be the correct answer because the touchUpInsideEvent was requested in the question – brainray Jun 03 '18 at 20:13
  • great answer.. except that it assumes that everyone uses storybuilder to build UI. False. – abbood Feb 04 '19 at 07:12
  • 1
    This is brilliant, and it does work without IB, if you just declare your class to inherit from UIControl instead of UIView, you can call addTarget! – biomiker Oct 06 '21 at 20:38
  • @biomiker you're right, its your choice to use IB or call addTarget!! Cheers happy coding. – Subhash Sharma Oct 07 '21 at 07:48
10

This will be better if we talking about swift3 or swift 4

let gesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(targetViewDidTapped))
gesture.numberOfTapsRequired = 1
targetView?.isUserInteractionEnabled = true
targetView?.addGestureRecognizer(gesture)
daxh
  • 571
  • 7
  • 14
8

you can use UITapGestureRecognizer, add it on view programmatically as follows

self.userInteractionEnabled = true
let gesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
gesture.numberOfTapsRequired = 1
self.addGestureRecognizer(gesture)

and implement the selector, You can also add gesture to view using xib or Interface Builder file.

Saif
  • 2,678
  • 2
  • 22
  • 38
6

In Swift 4 there is new syntax of init UITapGestureRecognizer:

let gesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("viewTapped:"))
// or declare like this
let gesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(YourClass.viewTapped(gesture:)))
yourView.addGestureRecognizer(gesture)
Agisight
  • 1,778
  • 1
  • 14
  • 15