简体   繁体   中英

Conflicting UITapGestureRecognizer in UIView and for UITableView

I have a UIView in which I added a UITapGestureRecognizer . Inside that view I also have a subview in which is basically some kind of a UITableView . The question is that why doesn't the UITableView recognizes the tap on a row, instead it goes to the tap gesture recognizer's handler all the time. Why is this, and how do I solve this? If I set the number of taps to 2, then it works fine. Any idea on how to solve this? Basically it doesn't call the didSelectRowAtIndexPath .

Set cancelsTouchesInView of your recognizer to NO . Otherwise, it "consumes" the touch for itself, and does not pass it on to the table view. That's why the selection event never happens.

If you want both your UITableView and your UITapGestureRecognizer to receive touch events, then yes the cancelsTouchesInView = NO will work. If you want the tap gesture recognizer not to receive the touch events meant for the table view it is slightly less easy but very do-able.

Basically when you are creating your gesture recognizer you set self as its delegate. Then you implement the gestureRecognizer:shouldReceiveTouch: delegate method. A basic implementation might look like this.

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    UITableView *tableView = self.tableView;
    CGPoint touchPoint = [touch locationInView:tableView];
    return ![tableView hitTest:touchPoint withEvent:nil];
}

Essentially this method (as implemented) asks the tableView if this touch's location falls within the tableView 's jurisdiction, and if it does, it will block the gesture recognizer from receiving the touch...allowing the tableView to receive the touch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM