如何向 UIView 添加触摸事件? [英] How to add a touch event to a UIView?

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

问题描述

如何向 UIView 添加触摸事件?
我试试:

How do I add a touch event to a UIView?
I try:

UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, nextY)] autorelease];
[headerView addTarget:self action:@selector(myEvent:) forControlEvents:UIControlEventTouchDown];
// ERROR MESSAGE: UIView may not respond to '-addTarget:action:forControlEvents:'

我不想创建子类并覆盖

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

推荐答案

在 iOS 3.2 及更高版本中,您可以使用手势识别器.例如,这是您处理点击事件的方式:

In iOS 3.2 and higher, you can use gesture recognizers. For example, this is how you would handle a tap event:

//The setup code (in viewDidLoad in your view controller)
UITapGestureRecognizer *singleFingerTap = 
  [[UITapGestureRecognizer alloc] initWithTarget:self 
                                          action:@selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleFingerTap];

//The event handling method
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
{
  CGPoint location = [recognizer locationInView:[recognizer.view superview]];

  //Do stuff here...
}

还有很多内置手势.查看有关 iOS 事件处理和 UIGestureRecognizer 的文档.我在 github 上还有一堆示例代码,可能会有所帮助.

There are a bunch of built in gestures as well. Check out the docs for iOS event handling and UIGestureRecognizer. I also have a bunch of sample code up on github that might help.

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

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