Custom UIView addTarget?

JayVDiyk picture JayVDiyk · Nov 2, 2015 · Viewed 13.9k times · Source

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.

Answer

Subhash Sharma picture Subhash Sharma · Nov 2, 2015

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+