您可以UITapGestureRecognizer
使用此代码将相同添加到多个视图。
步骤是:
- 首先我们用标签创建三个视图
- 然后我们创建
NSMutableArray
这个视图并将其添加到数组中
- 之后添加 UITapGestureRecognizer 以查看
- 在 UITapGestureRecognizer 方法中,我们检查视图的标签以区分哪个视图被点击。
以下是步骤的代码:
-(Void)viewDidLoad {
[super viewDidLoad];
//First create three View
UIView *view1 = [[UIView alloc] initWithFrame: CGRectMake (5 , 171, 152, 152)];
view1.tag = 1; //add tag to view
view1.backgroundColor = [UIColor whiteColor];
[self.view addSubview: view1];
UIView * view2 = [[UIView alloc] initWithFrame: CGRectMake ( 163, 171, 152, 152)];
view2.tag = 2; //add tag to view
view2.backgroundColor = [UIColor whiteColor];
[self.view addSubview: view2];
UIView * view3 = [[UIView alloc] initWithFrame: CGRectMake ( 5, 330, 152, 152)];
view2.tag = 3; //add tag to view
view2.backgroundColor = [UIColor whiteColor];
[self.view addSubview: view2];
//Now create mutable array to hold our view
NSMutableArray * ary=[[NSMutableArray alloc] init];
[ary addObject:view1];
[ary addObject:view2];
[ary addObject:view3];
//now we add tap gesture to view
for (UIView *view in ary) {
UITapGestureRecognizer * answerDoubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(answerDoubleTapped:)];
answerDoubleTapGesture.numberOfTapsRequired = 2;
[answer4View addGestureRecognizer:answerDoubleTapGesture];
}
}
-(void)answerDoubleTapped:(UITapGestureRecognizer *)recognizer {
//Check which view is tapped
switch (recognizer.view.tag) {
case 1:
{
NSLog(@"First View Tapped");
break;
}case 2:
{
NSLog(@"Second View Tapped");
break;
}case 3:
{
NSLog(@"Third View Tapped");
break;
}case 4:
{
NSLog(@"Forth View Tapped");
break;
}default:
{
break;
}
}
}