ios - 如何向 UIView 添加触摸事件?

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

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 及更高版本中,您可以使用手势识别器。例如,这是您处理点击事件的方式:

//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 上还有一堆示例代码这可能会有所帮助。

https://stackoverflow.com/questions/4660371/

相关文章:

ios - 不能在 Objective-C 中使用 Swift 类

objective-c - 如何将 Swift 代码导入到 Objective-C?

objective-c - 覆盖 isEqual : and hash 的最佳实践

ios - 退出 iPhone 应用程序的正确方法?

objective-c - 对于 Objective-C 中用于访问 NSMutable 字典的每个

objective-c - 问号和冒号是什么意思(?: ternary operator) mean

ios - 为什么当应用程序从后台返回时不会调用 viewWillAppear?

ios - 如何以编程方式确定我的应用程序是否在 iphone 模拟器中运行?

ios - 如何在 NSUserDefaults 中存储自定义对象

ios - 如何强制 NSLocalizedString 使用特定语言