【发布时间】:2011-08-02 05:32:47
【问题描述】:
我有 2 个 UIView。
第一个是父视图
第二个是子视图,
我们如何检测子视图何时被触摸?
或者我想在用户触摸子视图时触摸父视图,任何代码可以帮助我做到这一点?可以这样做吗?
因为我有一个Something Function,当其中一个被触摸时会调用它。
【问题讨论】:
标签: iphone xcode uiview subview
我有 2 个 UIView。
第一个是父视图
第二个是子视图,
我们如何检测子视图何时被触摸?
或者我想在用户触摸子视图时触摸父视图,任何代码可以帮助我做到这一点?可以这样做吗?
因为我有一个Something Function,当其中一个被触摸时会调用它。
【问题讨论】:
标签: iphone xcode uiview subview
这对我有用:
(链接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];
【讨论】: