UIAlertAction的处理程序有点晚,我该如何使其立即执行?

3
我正在尝试将声音效果添加到添加到UIAlertController的按钮中。我在处理程序中触发声音效果,但这实际上有点晚了。声音会比预期晚0.5秒左右。我希望声音在警报即将解除时立即触发,而不是在解除后触发。使用UIAlertView,可以使用alertWillDismiss而不是alertDidDismiss来处理此问题。 我错过了什么吗?

相关内容:https://dev59.com/I1wY5IYBdhLWcg3wl4sb?rq=1 - Jonny
如果您认为您有一个好的用例,请向苹果提交错误报告! - matt
我尝试登录bugreport.apple.com,但是我得到的只有发生了错误。如需访问Apple Bug Reporter的帮助,请联系Apple Developer Program Support。 我猜我被普遍憎恨了。或者我们所有人都是。 - Jonny
我猜他们没有添加这个功能是因为这个问题:https://dev59.com/3F8e5IYBdhLWcg3wPYhA - 如果在同一个uiviewcontroller中使用相同的uialertcontroller打开两个警报,则处理程序无法打开另一个uialertcontroller,如果上一个警报没有完全关闭。只是我的猜测。 - Jonny
3个回答

3
没有,你没有错过任何东西。你要寻找的功能不是由UIAlertController提供的。考虑提供自己的呈现视图控制器,通过它你可以得到你想要的精细控制。

值得注意的是,虽然子类化UIAlertController并覆盖viewWillDisappear可能很容易,但这个类在未来可能会变成final。 - Patrick Goley

2

我采用了Patrick Goley的建议,即继承UIAlertController并重写viewWillDisappear方法。对我来说效果很好。

//
//  ImmediateClickAlertController.swift
//
//  This subclass of UIAlertController plays a click immediately whenever it is dismissed (i.e. when a button is tapped).
//  This fixes an issue when trying to play a click in an attached UIAlertAction, which does not happen until after its view disappears.

import AudioToolbox

class ImmediateClickAlertController: UIAlertController {

    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        // play a click
        let pressKeySystemSoundID: SystemSoundID = 1104
        AudioServicesPlaySystemSound(pressKeySystemSoundID)
    }
}

-1

有点小技巧,但也许你可以:

  1. 尝试通过遍历(尽管是私有的)视图层次结构树来获取警报按钮的引用,并且
  2. 使用KVO检测其selected和/或highlighted属性的任何更改(我的经验是selected不可靠,而highlighted是)。

...但所有这些都相当脆弱,不够优雅,可能会在操作系统的未来版本中崩溃和/或被拒绝进入应用商店...?

因此,你最好的选择(即使是最费力的)是自己编写模态视图控制器:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接