问题是您显示了多个警报视图。您的长按处理程序将被调用不同的状态。
从文档中UILongPressGestureRecognizer
:
长按手势是连续的。当允许的手指数量 (numberOfTouchesRequired) 已按下指定时间段 (minimumPressDuration) 并且触摸移动未超出允许的移动范围 (allowableMovement) 时,手势开始 (UIGestureRecognizerStateBegan)。每当手指移动时,手势识别器就会转换为 Change 状态,并在任何手指抬起时结束 (UIGestureRecognizerStateEnded)。
因此,您最终会显示“开始”状态的警报,然后是“已更改”状态,最后是“结束”状态。如果你移动手指,你会得到一串“已更改”状态,并且最终也会为每个状态显示一个警报。
您需要决定何时真正希望出现警报。您希望它出现在第一个“已更改”状态,还是当用户抬起手指时出现“已结束”状态。
你的代码需要是这样的:
- (IBAction)longPressDetected1:(UIGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateEnded) {
// label1.text = @"Select Iran to observe its historical data projections ";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
message:@"Press the blue button (+) to select your region "
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
}
}
当用户抬起手指时,将显示警报。改变UIGestureRecognizerStateEnded
to UIGestureRecognizerStateChanged
如果您希望在识别到长按后立即出现警报。但请记住,您仍然可能会得到多个,因为长按可以生成多个“已更改”状态。在这种情况下,您需要添加一项额外的检查,以仅在尚无警报时显示警报。
实际上,这是支持“已更改”状态的单个警报的简单方法:
- (IBAction)longPressDetected1:(UIGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateChanged) {
sender.enabled = NO; // Prevent any more state updates so you only get this one
sender.enabled = YES; // reenable the gesture recognizer for the next long press
// label1.text = @"Select Iran to observe its historical data projections ";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
message:@"Press the blue button (+) to select your region "
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
}
}