jar*_*ryd 5 iphone uigesturerecognizer uitapgesturerecognizer
我有一个 UIButton,它有一个 IBAction 以及一个 UITapGestureRecognizer 来检测双击。
目前看来 IBAction 正在阻止识别器。有没有办法阻止这个或者 UITapGestureRecognizer 甚至可以在按钮上工作?如果是这样,添加识别器并删除 IBActions 不是更好吗?
编辑
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget : self action : @selector (handleDoubleTap:)];
[doubleTap setNumberOfTapsRequired:2];
[A1 addGestureRecognizer:doubleTap];
[A2 addGestureRecognizer:doubleTap];
[B1 addGestureRecognizer:doubleTap];
Run Code Online (Sandbox Code Playgroud)
小智 5
看起来您正在尝试将一个手势识别器附加到多个按钮。手势识别器一次只能附加到一个视图。因此,在您的情况下,您将识别器附加到的最后一个按钮(按钮 B1)可能会响应双击,但 A1 和 A2 不会响应。
为每个按钮创建一个单独的识别器。
但是所有三个识别器都可以调用相同的操作方法(handleDoubleTap:)。
但是,当您尝试单击按钮时,会出现轻微的延迟,因为它会等待查看是否是双击的开始。有多种方法可以减少延迟,但如果您可以忍受延迟并且解决方法会带来其他问题,则可能不值得。
编辑:
在您的评论中,您说您“想检测它们是否被同时按下”。为此,您不需要手势识别器。您可以只使用提供的标准控制事件。
接下来,在 IB 中,对于每个按钮,将“Touch Down”事件与 挂钩buttonPressed:。或者,以编程方式执行此操作:
[button1 addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
[button2 addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
[button3 addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
Run Code Online (Sandbox Code Playgroud)
接下来,在 IB 中,对于每个按钮,将“Touch Up Inside”和“Touch Up Outside”事件与挂钩buttonReleased:。或者,以编程方式执行此操作:
[button1 addTarget:self action:@selector(buttonReleased:) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchUpOutside];
[button2 addTarget:self action:@selector(buttonReleased:) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchUpOutside];
[button3 addTarget:self action:@selector(buttonReleased:) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchUpOutside];
Run Code Online (Sandbox Code Playgroud)
接下来,添加 ivars 来跟踪按下了多少个按钮或按下了哪些按钮:
@property (nonatomic) int numberOfButtonsBeingTouched;
@property (strong, nonatomic) NSMutableSet *buttonsBeingTouched; //alloc + init in viewDidLoad or similar
Run Code Online (Sandbox Code Playgroud)
如果您只关心按下了多少个按钮,则不需要NSMutableSet.
最后,添加buttonPressed和buttonReleased方法:
- (IBAction)buttonPressed:(UIButton *)button {
self.numberOfButtonsBeingTouched++;
[self.buttonsBeingTouched addObject:button];
//your logic here (if (self.numberOfButtonsBeingTouched == 3) ...)
}
- (IBAction)buttonReleased:(UIButton *)button {
self.numberOfButtonsBeingTouched--;
[self.buttonsBeingTouched removeObject:button];
//your logic (if any needed) here
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11157 次 |
| 最近记录: |