在UIView上触摸事件
一个非常普遍的方式是覆盖在自定义UIView子类这些方法:响应触摸EV下
- (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
官方的文档,这些方法是因为它是UIResponder的一个子类,所以UIView继承了这些方法 in the UIResponder class docs。更详细的介绍性文档可以在Event Handling Guide for iOS中找到。
如果您只想检测轻击(触摸,然后在视图中触摸),最简单的方法是将UIButton
作为视图的子视图添加,然后将自己的自定义方法添加为目标/动作为那个按钮配对。自定义按钮在默认情况下是不可见的,所以它不会影响视图的外观。
如果您正在寻找更高级的互动,那么了解the UIGestureRecognizer
class也是一件好事。
从您通过继承UIView
并重写子类中,下面的方法创建一个子类创建自己的自定义UIView
,
(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
}
获得触摸
在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];
而不是使用手势捕捉触摸,我会建议的UIView父类更改为UIControl,让它能够处理touchUpInside事件
来源:
@interface MyView : UIView
为:
@interface MyView : UIControl
,然后添加这一行视图 -
[self addTarget:self action:@selector(viewTapped:) forControlEvents:UIControlEventTouchUpInside];
因为手势可能会产生问题,同时滚动。
我的方法是在InterfaceBuilder IdentityInspector中简单地将UIView
更改为UIControl
类,那么ConnectionsInspector将立即使触摸事件准备好挂钩。
零码更改。
剪断第二码帮我,但更好的做法是'UITapGestureRecognizer * touchOnView = [[[UITapGestureRecognizer页头] initWithTarget:自我行动:@selector( releaseButAction :)] autorelease];'然后该方法将是' - (void)releaseButAction:(UIGestureRecognizer *)gestureRecognizer' ..只是fyi! – sixstatesaway 2013-01-09 10:13:40