UIGestureRecognizer for part of a UIView

前端 未结 2 734
说谎
说谎 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.

    0 讨论(0)
  • 2021-02-04 14:10

    Yo can also do:

    gestureRecognizer.delegate = self
    

    somewhere. generally on viewDidLoad(). then you implement the method:

     func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
            let view = self.getTheViewDontWannaConsider() /* or whateva */
    
            let point = touch.location(in:view)
            if point.y >= 50 /* or whateva calc. you want */ {
               return false
            }
            return true
        }
    
    0 讨论(0)
提交回复
热议问题