Ios 在UILongPressGestureRecognitor上无法检测右(按下)按钮?
关于SO(),答案很少,但我无法用下面的代码获得正确的值,不确定我做错了什么。在SO和类似的第三方网站教程上尝试了更多页面,但无法获得确切的按钮细节Ios 在UILongPressGestureRecognitor上无法检测右(按下)按钮?,ios,objective-c,uigesturerecognizer,Ios,Objective C,Uigesturerecognizer,关于SO(),答案很少,但我无法用下面的代码获得正确的值,不确定我做错了什么。在SO和类似的第三方网站教程上尝试了更多页面,但无法获得确切的按钮细节 @property (nonatomic,strong) UILongPressGestureRecognizer *lpgr; @property (strong, nonatomic) IBOutlet UIButton *button1; @property (strong, nonatomic) IBOutlet UIButton *but
@property (nonatomic,strong) UILongPressGestureRecognizer *lpgr;
@property (strong, nonatomic) IBOutlet UIButton *button1;
@property (strong, nonatomic) IBOutlet UIButton *button2;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGestures:)];
self.lpgr.minimumPressDuration = 2.0f;
self.lpgr.allowableMovement = 100.0f;
[self.view addGestureRecognizer:self.lpgr];
}
- (void)handleLongPressGestures:(UILongPressGestureRecognizer *)gesture
{
if ([gesture isEqual:self.lpgr]) {
if (gesture.state == UIGestureRecognizerStateBegan)
{
if (gesture.view == self.button1) {
NSLog(@"Button 1 is pressed for long");
}else if(gesture.view == self.button2) {
NSLog(@"Button 2 is pressed for long");
}else{
NSLog(@"another UI element is pressed for long");
}
}
}
}
每次长时间按下按钮,我都会得到NSLog(@“另一个UI元素被长时间按下”) 每次都会命中else语句,因为您正在将手势添加到主视图中。即使您长按按钮,事件也会传递到您正在捕捉它的视图。如果在viewDidLoad中添加下面的行,它将在相应的按钮上触发
[self.button1 addGestureRecognizer:self.lpgr];
[self.button2 addGestureRecognizer:self.lpgr];
您已将手势添加到self.view,而不是button1/button2。如果我按1和2顺序添加上述行,则只会检测到button2长按手势。当我添加2和1时,仅检测到按钮1长按手势。我向单个按钮添加了手势,但仅触发组中的最后一个按钮手势,这基于下面的示例。