小编典典

如何向 UIView 添加触摸事件?

all

如何向 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

阅读 82

收藏
2022-04-25

共1个答案

小编典典

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

2022-04-25