【发布时间】:2011-05-07 00:58:57
【问题描述】:
有没有人有任何示例代码来检测动态创建的 UIView 上的触摸?我找到了一些对 touchesBegan 的引用,但不知道如何实现它...
【问题讨论】:
标签: ios objective-c iphone uikit
有没有人有任何示例代码来检测动态创建的 UIView 上的触摸?我找到了一些对 touchesBegan 的引用,但不知道如何实现它...
【问题讨论】:
标签: ios objective-c iphone uikit
一种非常通用的接触方式是在自定义 UIView 子类中覆盖这些方法:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
这些方法的官方文档位于the UIResponder class docs 的Responding to Touch Events 下(UIView 继承了这些方法,因为它是 UIResponder 的子类)。更长和更多的介绍性文档可以在Event Handling Guide for iOS 中找到。
如果您只想检测点击(在您的视图中触摸,然后触摸),最简单的方法是添加 UIButton 作为视图的子视图,并添加您自己的自定义方法作为目标/该按钮的操作对。自定义按钮默认不可见,因此不会影响视图的外观。
如果您正在寻找更高级的交互,也可以了解the UIGestureRecognizer class。
【讨论】:
在 UIView 上使用 UIAnimation 创建触摸事件,您可以在任何地方管理 UIView 上的触摸。
以下代码:这里 self.finalScore 是 UIView ,而 cup 是 UIImageView 。我处理
UIImageView 上的触摸事件,它出现在 UIView 中。
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch1 = [touches anyObject];
CGPoint touchLocation = [touch1 locationInView:self.finalScore];
CGRect startRect = [[[cup layer] presentationLayer] frame];
CGRectContainsPoint(startRect, touchLocation);
[UIView animateWithDuration:0.7
delay:0.0
options:UIViewAnimationCurveEaseOut
animations:^{cup.transform = CGAffineTransformMakeScale(1.25, 0.75);}
completion:^(BOOL finished) {
[UIView animateWithDuration:2.0
delay:2.0
options:0
animations:^{cup.alpha = 0.0;}
completion:^(BOOL finished) {
[cup removeFromSuperview];
cup = nil;}];
}];
}
像 UITapGestureRecognizer 是处理 UIView 上的触摸事件的另一种方式 ....
UITapGestureRecognizer *touchOnView = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(releaseButAction)] autorelease];
// Set required taps and number of touches
[touchOnView setNumberOfTapsRequired:1];
[touchOnView setNumberOfTouchesRequired:1];
// Add the gesture to the view
[[self view] addGestureRecognizer:touchOnView];
【讨论】:
UITapGestureRecognizer *touchOnView = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(releaseButAction:)] autorelease];,然后方法是- (void)releaseButAction:(UIGestureRecognizer *)gestureRecognizer..仅供参考!
我的方法是简单地将InterfaceBuilder IdentityInspector 中的UIView 类更改为UIControl 类,然后ConnectionsInspector 将立即为hook 准备好触摸事件。
零代码更改。
【讨论】:
我建议不要使用手势捕获触摸,而是将 UIView 父类更改为 UIControl,以便它可以处理 touchUpInside 事件
发件人:
@interface MyView : UIView
收件人:
@interface MyView : UIControl
然后添加这一行以供查看-
[self addTarget:self action:@selector(viewTapped:) forControlEvents:UIControlEventTouchUpInside];
因为手势可能会在滚动时产生问题。
【讨论】:
从您通过继承UIView 创建的子类创建您自己的自定义UIView,并在子类中覆盖以下方法,
(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
}
【讨论】: