我是IOS Dev的新手,正在为UIView搜索onclick事件,我发现这个代码完美无缺。但它并没有调用特定的UIView,因为我使用多个UIViews并希望分别在所有这些上添加事件,而这段代码调用了UIView的handleSingleTap onclick。请帮助..
- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *singleFingerTap =
[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleFingerTap];
}
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer {
CGPoint location = [recognizer locationInView:[recognizer.view superview]];
NSLog(@"Clicked");
}
答案 0 :(得分:0)
您可以创建UITapGestureRecognizer
并将其添加到您希望点击的视图中。
您还可以在每个视图上设置标记属性,以找出单击的视图。
例如:
UITapGestureRecognizer *singleFingerTap1 =
[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
view1.tag = 1;
[view1 addGestureRecognizer:singleFingerTap1];
UITapGestureRecognizer *singleFingerTap2 =
[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
view2.tag = 2;
[view2 addGestureRecognizer:singleFingerTap2];
//..and so on
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer {
UIView *viewClicked = recognizer.view;
NSLog(@"Clicked: %d", viewClicked.tag);
}
另一个解决方案是在主视图中添加一个手势识别器(保存其他视图的视图,发布的内容)和handleSingleTap
:方法检查点是否在视图内:
BOOL isPointInsideView1 = [view1 pointInside:location withEvent:nil];
BOOL isPointInsideView2 = [view1 pointInside:location withEvent:nil];
但是当一个视图覆盖另一个视图时,ic可能会失败。