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.
There is an easy way to achieve this.
- Go to Interface builder of your class
- Select the view u want to add action
- 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+
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)
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With