问题
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:
- Try and grab a reference to the alert's button (by traversing the -admittedly private- view hierarchy tree), and
- Use KVO to detect any changes to its
selected
and/orhighlighted
properties (my own experience is thatselected
is not reliably observable, whilehighlighted
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 embeddedUIActivityIndicator
- 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