版本記錄
版本號 | 時間 |
---|---|
V1.0 | 2017.06.02 |
前言
一般我們用的app很多都有手勢操作,特別是點擊手勢,很多時候我們有個需求:就是要父視圖響應點擊手勢,但是要求某個子視圖不響應點擊手勢。感興趣的可以看看我寫的其他小技巧
1. 實用小技巧(一):UIScrollView中上下左右滾動方向的判斷
2. 實用小技巧(二):屏幕橫豎屏的判斷和相關邏輯
詳情
下面我就以一個demo來說明這種情況的解決方法。
一、解決方案
在手勢的代理方法中,判斷event的view,如果是要屏蔽的子視圖就返回NO,其他就返回YES,這樣子就實現了父視圖響應手勢,但是某個子視圖不響應手勢,也就是說子視圖被屏蔽了。
二、代碼實現
下面我們就直接看代碼。
JJTapGestureVC.m
#import "JJTapGestureVC.h"
@interface JJTapGestureVC () <UIGestureRecognizerDelegate>
@property (nonatomic, strong) UIView *childView;
@property (nonatomic, strong) UITapGestureRecognizer *tapGesture;
@end
@implementation JJTapGestureVC
#pragma mark - Override Base Function
- (void)viewDidLoad
{
[super viewDidLoad];
[self setupUI];
}
#pragma mark - Object Private Function
- (void)setupUI
{
self.view.backgroundColor = [UIColor lightGrayColor];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureDidTapped)];
tapGesture.delegate = self;
self.tapGesture = tapGesture;
[self.view addGestureRecognizer:tapGesture];
UIView *childView = [[UIView alloc] initWithFrame:CGRectMake(50, 200, 200, 200)];
[self.view addSubview:childView];
childView.backgroundColor = [UIColor blueColor];
self.childView = childView;
}
#pragma mark - Action && Notification
- (void)tapGestureDidTapped
{
NSLog(@"我是父視圖");
}
#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if ([touch.view isDescendantOfView:self.childView]) {
return NO;
}
return YES;
}
@end
下面看結果gif
實現結果
結論:從上可以看出來,當我們點擊父視圖的時候會輸出:我是父視圖。但是點擊藍色的子視圖,就沒有輸出了,也就是說子視圖屏蔽了手勢。
后記
上面又是一個實用小技巧,后面我還會持續更新,希望大家喜歡,待續哦~~~
風景