20
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UITapGestureRecognizer subviewsのタップジェスチャーを無効にする

Posted at

UITapGestureRecognizerを加えたViewのsubviewsに対するタップジェスチャーを無効にする方法です。


viewAのsubviewsには、viewBとviewCが配置し、viewAにはUITapGestureRecognizerを加えています。

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewADidTap)];
[self.viewA addGestureRecognizer:tap];

ss

上記の設定でviewAをタップすると- (void)viewADidTapが呼ばれます。
viewB、viewCの領域内をタップした場合にも- (void)viewADidTapが呼ばれます。
これをviewB、viewCの領域内をタップした時に- (void)viewADidTapを呼ばないようにする方法です。

実装

ViewController.m
#import "ViewController.h"

@interface ViewController () <UIGestureRecognizerDelegate>

@property (weak, nonatomic) IBOutlet UIView *viewA;
@property (weak, nonatomic) IBOutlet UIView *viewB;
@property (weak, nonatomic) IBOutlet UIView *viewC;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewADidTap)];
    tap.delegate = self;
    [self.viewA addGestureRecognizer:tap];
}

/* タッチジェスチャーを発生させるかどうかを返す実装をする */
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
	/* タッチイベントが発生したビューとviewB, viewCを比較する */
    if (touch.view == self.viewB || touch.view == self.viewC) {
		// viewB, viewCの場合ジェスチャーを許可しない
        return NO;
    }
    return YES;
}

- (void)viewADidTap
{
    NSLog(@"viewA");
}

@end
20
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?