Iphone 如何在子视图中检测事件触摸,或者如何在触摸子视图时使父视图被触摸?
我有两种观点 第一个是父视图 第二个是子视图 我们如何检测子视图何时被触摸 或者我想让父视图在用户触摸子视图时被触摸,有什么代码可以帮我做吗?有可能这样做吗 因为我有一个Something函数,当其中一个被触摸时,它将调用。这可能会有帮助:Iphone 如何在子视图中检测事件触摸,或者如何在触摸子视图时使父视图被触摸?,iphone,xcode,uiview,subview,Iphone,Xcode,Uiview,Subview,我有两种观点 第一个是父视图 第二个是子视图 我们如何检测子视图何时被触摸 或者我想让父视图在用户触摸子视图时被触摸,有什么代码可以帮我做吗?有可能这样做吗 因为我有一个Something函数,当其中一个被触摸时,它将调用。这可能会有帮助: UITouch *touch = [event.allTouches anyObject]; CGPoint touchPoint = [touch locationInView:YOUR VIEW NAME]; 要检测触摸事件,您需要在子视图或超级视图(
UITouch *touch = [event.allTouches anyObject];
CGPoint touchPoint = [touch locationInView:YOUR VIEW NAME];
要检测触摸事件,您需要在子视图或超级视图(您希望在其中获得触摸)中添加
UITapGestureRecognitizer
然后,您可以添加UITapGestureRecognitizer
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch *touch = [touches anyObject];
// here you can get your touch
NSLog(@"Touched view %@",[touch.view class] );
}
希望它能给你一些想法。这对我很有用:
(链接xib或故事板中的子视图)
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中有一个选项。有一个复选框(标题为“已启用用户交互”)指定子视图是否处理用户事件
取消选中该复选框,所有对子视图的触摸都会转到父视图或其后面的任何其他视图。在handleTap函数中,我添加了以下行以隐藏键盘。[自视图编辑:是];那个复选框的名字是什么?我不再为iPhone编写代码了,我已经忘记了。我认为这是UIControl和UIView之间的主要区别。默认情况下,UIControl已启用该复选框。
@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