iosobjective-ceventsuiviewtouch

How to add a touch event to a UIView?


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

Solution

  • In iOS 3.2 and higher, you can use gesture recognizers. For example, this is how you would handle a tap event:

    //The setup code (in viewDidLoad in your view controller)
    UITapGestureRecognizer *singleFingerTap = 
      [[UITapGestureRecognizer alloc] initWithTarget:self 
                                              action:@selector(handleSingleTap:)];
    [self.view addGestureRecognizer:singleFingerTap];
    
    //The event handling method
    - (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
    {
      CGPoint location = [recognizer locationInView:[recognizer.view superview]];
    
      //Do stuff here...
    }
    

    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.