我如何添加一个触摸事件到一个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
你可以通过在代码中添加手势识别器来实现这一点。
步骤1:ViewController.m:
// Declare the Gesture.
UITapGestureRecognizer *gesRecognizer = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(handleTap:)];
gesRecognizer.delegate = self;
// Add Gesture to your view.
[yourView addGestureRecognizer:gesRecognizer];
步骤2:ViewController.m:
// Declare the Gesture Recogniser handler method.
- (void)handleTap:(UITapGestureRecognizer *)gestureRecognizer{
NSLog(@"Tapped");
}
注意:这里的yourView在我的情况是@property(强,非原子)IBOutlet UIView *localView;
编辑:*localView是Main中的白色框。下面的故事板