gpt4 book ai didi

ios - 是否可以响应 UIAlertView 中的摇动手势?

转载 作者:搜寻专家 更新时间:2023-10-30 20:18:27 24 4
gpt4 key购买 nike

我有一个 UIAlertView,它会弹出一条消息和一个按钮“继续”。我想要的是摇动手势也会调用与点击继续按钮相同的代码。但是,我不确定这是否适用于 iOS7 中的 UIAlertView,或者我是否必须创建自己的自定义警报 View 。

我已经尝试实现:

(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { ... }

canBecomeFirstResponder { return YES; }

但是当它们在主视图设置为 becomeFirstResponder 时正常工作时,一旦 UIAlertView 弹出,它们就不会响应。那么,我尝试在 UIAlertView+MotionResponder.h 的类别中实现这些以尝试扩展 UIAlertView,但是 motionEnded 没有被调用即使 canBecomeFirstResponder 正确返回 YES

那么这应该有效吗?还是我必须实现自己的警报 View ?

最佳答案

根据documentation

The UIAlertView class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified.

UIAlertView 的内部 View 层次结构比它看起来复杂得多,从 iOS 7 开始,它甚至没有添加到任何 UIWindow 中,因此不足为奇它没有像您预期的那样参与响应者链。

但是,您可能会考虑在 Controller 中实现 Action 识别逻辑,并让它触发 UIAlertView 关闭。

您只需要保持对 UIAlertView 实例的引用,检测 Controller 中的摇动手势并发送一个 –dismissWithClickedButtonIndex:animated: 消息到警报,在命令将其驳回。

编辑

UIAlertView 出现在当前 Controller 的顶部时,上述技术将不起作用,因为它会拦截摇动手势并且永远不会调用 Controller 方法。

要使其正常工作,您必须在窗口级别检测手势。这是您可以如何做的一个简短示例。

首先,我们在 UIWindow 上定义一个类别,它拦截摇动手势并广播通知(我将只发布 @implementation,因为 @interface 为空)

@implementation UIWindow (Shake)
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if (event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"UIWindowDidShake" object:nil userInfo:nil];
}
}}
@end

然后在 Controller 中,我们在显示警报时注册到通知,并在通知到达时解除警报。最后,一旦警报被解除,我们就可以从观察者中移除 Controller 。

@property (nonatomic, strong) UIAlertView *alert;

...

- (IBAction)showAlert:(id)sender {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissAlert) name:@"UIWindowDidShake" object:nil];
self.alert = [[UIAlertView alloc] initWithTitle:nil message:@"An alert" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[self.alert show];
}

- (void)dismissAlert {
[self.alert dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"UIWindowDidShake" object:nil];
}

关于ios - 是否可以响应 UIAlertView 中的摇动手势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20341572/

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