The handler of a UIAlertAction is a bit too late - how can I make it immediate?

孤者浪人 提交于 2019-12-07 12:29:21

问题


I am trying (...) to add a sound effect to the buttons added to a UIAlertController. I fire a sound effect in the handler, but this actually is a bit too late. The sound fires like 0.5 seconds too late. I want the sound to fire as soon as the alert is about to dismiss, not after it has dismissed. With UIAlertView this was possible to handle using alertWillDismiss... rather than alertDidDismiss.

Did I miss something?


回答1:


No, you didn't miss anything. The functionality you're looking for is not provided by UIAlertController. Consider providing your own presented view controller, over which you'll have the kind of fine control you're after.




回答2:


I used Patrick Goley's suggestion, namely to subclass UIAlertController and override viewWillDisappear. Worked great for me.

//
//  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)
    }
}



回答3:


A bit of a hackery, but perhaps you could:

  1. Try and grab a reference to the alert's button (by traversing the -admittedly private- view hierarchy tree), and
  2. Use KVO to detect any changes to its selected and/or highlighted properties (my own experience is that selected is not reliably observable, while highlighted is).

...but all of this is quite fragile, not elegant, maight break in a future release of the OS and/or get you rejected from the app store...?

So you're best option (even if the most laborious) is to roll your own modal view controller:

  • Apple's documentation on presenting modal view controllers.

  • Demo project I made following the above docs (a custom "UIAlertController look-alike" with an embedded UIActivityIndicator - for use during long, asynchronous processes):



来源:https://stackoverflow.com/questions/35447399/the-handler-of-a-uialertaction-is-a-bit-too-late-how-can-i-make-it-immediate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!