【发布时间】:2015-12-16 22:55:59
【问题描述】:
我有一个计算器应用程序,我想根据用户长按的计算器按钮显示不同的警报视图文本。我有工作长触摸代码。如何识别长按发生在哪个计算器按钮上?
-(void)handleLongTapGesture:(UITapGestureRecognizer *)sender{
if (sender.state == UIGestureRecognizerStateEnded) {
}
else if (sender.state == UIGestureRecognizerStateBegan){
// The alert view text should change, depending on which calculator button is long touched
UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"I want the alert view text to change according to what calculator button is long touched"
message: @""
delegate: self
cancelButtonTitle:nil
otherButtonTitles:@"OK", nil];
[alert setTag:1];
[alert show];
}
}
// This code only produces a set of X-Y coordinates if the User touches between calculator buttons, not on the button itself
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:touch.view];
NSLog(@"location.x = %f", location.x);
NSLog(@"location.y = %f", location.y);
}
【问题讨论】:
-
你有一个点击手势识别器(在超级视图上设置),还是每个按钮一个?在第一种情况下,您可以使用
hitTest:withEvent:找到水龙头下的视图。在另一种情况下,您可以简单地使用识别器的view属性... -
我目前有一个长触摸手势识别器。每个按钮都需要手势识别器吗?我也一直在尝试获取长按按钮的标签,但没有成功。而且我也尝试过hitTest,但无法检测到使用它的按钮长按。明天将继续努力寻找解决方案。
-
不,您不需要为每个按钮一个。您可以为每个按钮设置一个(在这种情况下,您可以使用
view属性来查找所述按钮)。或者,如果您只有一个识别器,请使用locationInView:获取位置,然后使用hitTest:withEvent:查找视图。 -
我现在有一个使用视图属性的工作解决方案,正如您所建议的那样。我几乎可以肯定我昨天尝试过,但无法让它工作。无论如何,感谢您对此事的帮助。
-
我用这个创建了一个答案(实际上有两个选项),如果有帮助,请随时投票和/或接受它。