UIView 上的触摸事件

Touch Event on UIView(UIView 上的触摸事件)

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

问题描述

有没有人有任何示例代码来检测动态创建的 UIView 上的触摸?我找到了一些对 touchesBegan 的引用,但不知道如何实现它...

解决方案

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

这些方法的官方文档位于 Responding to Touch Events 下>UIResponder 类文档(UIView 继承了这些方法,因为它是 UIResponder 的子类).在 iOS 事件处理指南中可以找到更长和更多的介绍性文档..p>

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

如果您正在寻找更高级的交互,最好了解 UIGestureRecognizer 类.

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

解决方案

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

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.

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.

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

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

本文标题为:UIView 上的触摸事件

基础教程推荐