gpt4 book ai didi

ios - UIAlertView 警报在长按手势识别器中重复三次

转载 作者:行者123 更新时间:2023-11-28 18:03:53 25 4
gpt4 key购买 nike

我创建了一个应用程序。通过开发它,我使用长按按钮来显示警报。

这是我的代码:

- (IBAction)longPressDetected1:(UIGestureRecognizer *)sender {
// 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];
}

问题:当我想使用cancelIbutton 取消UIAlertView 时,我必须按三次这个按钮才能取消UIAlertView。这意味着 UIAlterview 不能被一键取消。你能帮帮我吗?

最佳答案

问题是您显示的警报 View 不止一个。您的长按处理程序将针对不同的状态被调用。

来自 UILongPressGestureRecognizer 的文档:

Long-press gestures are continuous. The gesture begins (UIGestureRecognizerStateBegan) when the number of allowable fingers (numberOfTouchesRequired) have been pressed for the specified period (minimumPressDuration) and the touches do not move beyond the allowable range of movement (allowableMovement). The gesture recognizer transitions to the Change state whenever a finger moves, and it ends (UIGestureRecognizerStateEnded) when any of the fingers are lifted.

因此,您最终会显示“开始”状态的警报,然后是“已更改”状态的警报,然后再次显示“结束”状态的警报。如果您四处移动手指,您会看到一连串“已更改”状态,并且您最终也会为每个状态显示一个警报。

您需要决定何时真正希望提醒出现。您是想让它出现在第一个“已更改”状态,还是在用户抬起手指时出现“已结束”状态。

您的代码需要是这样的:

- (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 更改为 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];
}
}

关于ios - UIAlertView 警报在长按手势识别器中重复三次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15306942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com