如何将touch 事件添加到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

推荐答案

在iOS3.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的示例代码,它们可能会有所帮助.

Ios相关问答推荐

如何修复使用EFCore和SQLite的.Net MAUI iOS应用程序上的当前应用程序不支持NullabilityInfoContext?

无法在所有窗口上方显示图像

在SwiftUI中插入绘制重复形状

带有故事板的Xcode 15 UIKit视图可以与#Preview宏一起使用吗?

当操作修改查看条件时,按钮不重复

如何在iOS 17 SwiftUI中获取用户名

如何为 Firebase Auth 实施 Firebase AppCheck?

如何使用 Rxswift 处理程序最喜欢的按钮

Swift Combine和iOS版本限制?

Toast 不显示 Flutter

SKScene 的更新功能似乎不起作用

Task.cancel() 的 TaskPriority 的区别

SwiftUI 中的描边图像边框

如何在 SwiftUI 的 TabView 中添加底部曲线?

SwiftUI 文本字段代理绑定代码忽略空格不起作用?

如何使用 sendAsynchronousRequest:queue:completionHandler:

在 iOS 7 上更改标签栏色调 colored颜色

如何确定 WKWebView 的内容大小?

UINavigationBar - 以编程方式设置标题?

从故事板导航到其他 Swift 1.2 文件时 Xcode 6.3 崩溃