UIGestureRecognizer for part of a UIView

前端 未结 2 736
说谎
说谎 2021-02-04 13:37

I\'m using UIGestureRecognizer in my iOS application and I\'m having some issues.

I only want the gestures to work in a certain area of the view, so I made a new UIView

2条回答
  •  余生分开走
    2021-02-04 14:10

    Don't create a new view for your gesture recognizer. The recognizer implements a locationInView: method. Set it up for the view that contains the sensitive region. On the handleGesture, hit-test the region you care about like this:

    0) Do all this on the view that contains the region you care about. Don't add a special view just for the gesture recognizer.

    1) Setup mySensitiveRect

    @property (assign, nonatomic) CGRect mySensitiveRect;
    @synthesize mySensitiveRect=_mySensitiveRect;
    self.mySensitiveRect = CGRectMake(0.0, 240.0, 320.0, 240.0);
    

    2) Create your gestureRecognizer:

    gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
    [self.view addGestureRecognizer:gr];
    // if not using ARC, you should [gr release];
    // mySensitiveRect coords are in the coordinate system of self.view
    
    
    - (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer {
        CGPoint p = [gestureRecognizer locationInView:self.view];
        if (CGRectContainsPoint(mySensitiveRect, p)) {
            NSLog(@"got a tap in the region i care about");
        } else {
            NSLog(@"got a tap, but not where i need it");
        }
    }
    

    The sensitive rect should be initialized in myView's coordinate system, the same view to which you attach the recognizer.

提交回复
热议问题