[英]how to detect event touch in subview or how to make parent view was touched when we touch subview?
我有2个UIView。
第一个是父视图
第二个是子视图,
我们如何检测子视图何时触及?
或者我想让用户触摸子视图时触摸父视图,任何代码都可以帮我做到吗? 是否有可能做到这一点?
因为我有一个Something Function,当其中一个被触摸时会调用。
这对我有用:
(在xib或storyboard中链接子视图)
ViewController.h
@interface ViewController : UIViewController
@property (nonatomic, strong) IBOutlet UIView *subview;
@property (nonatomic, strong) UITapGestureRecognizer *tapRecognizer;
@end
ViewController.m
@implementation ViewController
@synthesize subview;
@synthesize tapRecognizer;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handleTap:)];
[subview addGestureRecognizer:tapRecognizer];
}
- (IBAction)handleTap:(UITapGestureRecognizer *)recognizer {
if (recognizer.state == UIGestureRecognizerStateEnded){
//code here
NSLog(@"subview touched");
}
}
@end
问题已经解决了。 我觉得有人给了一个很好的答案,但我忘记了。
这就是我做的。 XIB中有一个选项。 有一个复选框(标题为“启用了用户交互”),指定子视图是否处理用户事件。
取消选中该复选框,并且所有触摸子视图都会转到父视图或其后的任何其他视图。
要检测触摸事件,您需要在子视图或超级视图中添加UITapGestureRecognizer
(您需要在其中进行触摸)。
- (void)viewDidLoad
{
UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(tap:)];
tap.numberOfTapsRequired = 1;
[self addGestureRecognizer:tap];
[super viewDidLoad];
}
然后你可以添加UITapGestureRecognizer
委托方法
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch *touch = [touches anyObject];
// here you can get your touch
NSLog(@"Touched view %@",[touch.view class] );
}
希望它能给你一些想法......
这可能有所帮助:
UITouch *touch = [event.allTouches anyObject];
CGPoint touchPoint = [touch locationInView:YOUR VIEW NAME];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.