触摸UIView上的事件

有没有人有任何示例代码来检测dynamic创build的UIView触摸? 我已经findtouchesBegan的一些引用,但无法弄清楚如何实现它…

一个非常通用的方法是在自定义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 

这些方法的官方文档是在UIResponder类文档中 响应触摸事件 (UIViewinheritance那些方法,因为它是UIResponder的子类)。 iOS事件处理指南中提供了更长和更多介绍性文档。

如果你只是想检测点击(触摸,然后在你的视图中修改),最简单的方法是添加一个UIButton作为你的视图的子视图,并添加自己的自定义方法作为该button的目标/动作对。 自定义button在默认情况下是不可见的,所以它不会影响视图的外观。

如果您正在寻找更高级的交互,那么了解UIGestureRecognizer类也是一件好事。

在UIView上用UIAnimation创build触摸事件,你可以在任何地方pipe理UIView上的触摸。

以下代码:这里self.finalScore是一个UIView,而杯子是一个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]; 

从通过inheritanceUIView创build的子类中创build自己的自定义UIView ,并在子类中重写以下方法,

 (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ } 

我的方法是简单地将UIView更改为InterfaceBuilder IdentityInspector中的UIControl类,然后ConnectionsInspector将立即将触摸事件准备好挂钩。

零代码更改。

而不是使用手势捕捉触摸,我build议将UIView父类更改为UIControl,以便它可以处理touchUpInside事件

从:

 @interface MyView : UIView 

至:

 @interface MyView : UIControl 

然后添加这一行视图 –

  [self addTarget:self action:@selector(viewTapped:) forControlEvents:UIControlEventTouchUpInside]; 

由于手势在滚动时可能会产生问题。

通过大气识别器,可以很容易地发现触摸事件。

在故事板中查找一个从组件库中获得的值:

在这里输入图像说明

例如,将Tap Gesture识别器拖到您的视图中。 它不显示在视图UI中。 您可以从故事板左侧面板中的文档大纲中find它:

在这里输入图像说明

最后一步是通过控制拖拽的方式将其链接到视图,作为监视触摸的委托,然后将控件拖到视图控制器类中作为一个动作。 这是链接连接的图片。

在这里输入图像说明

和行动代码:

 @IBAction func tapAction(_ sender: Any) { // touch is captured here. }