在UIView上触摸事件 [英] Touch Event on UIView

查看:96
本文介绍了在UIView上触摸事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有人有任何示例代码用于检测动态创建的UIView上的触摸?我找到了一些对touchesBegan的引用,但无法弄清楚如何实现它...

Does anyone have any sample code for detecting touches on a dynamically created UIView? I have found some references to touchesBegan but cannot figure out how to implement it...

推荐答案

一种非常通用的方式来获取触摸是在自定义UIView子类中重写这些方法:

A very general way to get touches is to override these methods in a custom UIView subclass:

- (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

这些方法的官方文档位于响应触摸事件下/Reference.html#//apple_ref/occ/cl/UIResponderrel =noreferrer> UIResponder类文档(UIView继承了这些方法,因为它是UIResponder的子类)。可以在适用于iOS的事件处理指南

The official docs for these methods is under Responding to Touch Events in the UIResponder class docs (UIView inherits those methods since it's a subclass of UIResponder). Longer and more introductory docs can be found in the Event Handling Guide for iOS.

如果您只想检测点按(触摸,然后触摸)在您的视图中,最简单的方法是添加 UIButton 作为视图的子视图,并添加自己的自定义方法作为该按钮的目标/操作对。默认情况下,自定义按钮是不可见的,因此不会影响视图的外观。

If you just want to detect a tap (touch-down, then touch-up within your view), it's easiest to add a UIButton as a subview of your view, and add your own custom method as a target/action pair for that button. Custom buttons are invisible by default, so it wouldn't affect the look of your view.

如果您正在寻找更高级的互动,那么了解它也很有用 UIGestureRecognizer 上课

If you're looking for more advanced interactions, it's also good to know about the UIGestureRecognizer class.

这篇关于在UIView上触摸事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆