How do I add a touch event to a UIView?
I try:
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, nextY)] autorelease];
[headerView addTarget:self action:@selector(myEvent:) forControlEvents:UIControlEventTouchDown];
// ERROR MESSAGE: UIView may not respond to '-addTarget:action:forControlEvents:'
I don't want to create a subclass and overwrite
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
You can achieve this by adding Gesture Recogniser in your code.
Step 1: ViewController.m:
Step 2: ViewController.m:
NOTE: here yourView in my case was
@property (strong, nonatomic) IBOutlet UIView *localView;
EDIT: *localView is the white box in Main.storyboard from below
Heres a Swift version:
I think you can simply use
i mean headerView extends from UIControl.
In iOS 3.2 and higher, you can use gesture recognizers. For example, this is how you would handle a tap event:
There are a bunch of built in gestures as well. Check out the docs for iOS event handling and
UIGestureRecognizer
. I also have a bunch of sample code up on github that might help.Gesture Recognizers
There are a number of commonly used touch events (or gestures) that you can be notified of when you add a Gesture Recognizer to your view. They following gesture types are supported by default:
UITapGestureRecognizer
Tap (touching the screen briefly one or more times)UILongPressGestureRecognizer
Long touch (touching the screen for a long time)UIPanGestureRecognizer
Pan (moving your finger across the screen)UISwipeGestureRecognizer
Swipe (moving finger quickly)UIPinchGestureRecognizer
Pinch (moving two fingers together or apart - usually to zoom)UIRotationGestureRecognizer
Rotate (moving two fingers in a circular direction)In addition to these, you can also make your own custom gesture recognizer.
Adding a Gesture in the Interface Builder
Drag a gesture recognizer from the object library onto your view.
Control drag from the gesture in the Document Outline to your View Controller code in order to make an Outlet and an Action.
This should be set by default, but also make sure that User Action Enabled is set to true for your view.
Adding a Gesture Programmatically
To add a gesture programmatically, you (1) create a gesture recognizer, (2) add it to a view, and (3) make a method that is called when the gesture is recognized.
Notes
sender
parameter is optional. If you don't need a reference to the gesture then you can leave it out. If you do so, though, remove the(sender:)
after the action method name.handleTap
method was arbitrary. Name it whatever you want usingaction: #selector(someMethodName(sender:))
.More Examples
You can study the gesture recognizers that I added to these views to see how they work.
Here is the code for that project:
Notes
Another way is adding a transparent button to the view
And then, handle click: