Skip to content

Instantly share code, notes, and snippets.

@aokj4ck
Last active August 29, 2015 14:09
Show Gist options
  • Save aokj4ck/2e07b633b203831475d5 to your computer and use it in GitHub Desktop.
Save aokj4ck/2e07b633b203831475d5 to your computer and use it in GitHub Desktop.
Swift class extension on UIViewController using the navigation item to display a toast for a given number of seconds.
import UIKit
import Dispatch
struct PromptToast {
static let ErrorMessageDisplayDuration = 5.2
}
extension UIViewController {
func toast(message: String, duration: Double) {
/* Make sure we have a navigation controller */
if let n = navigationController {
navigationItem.prompt = message
let mainQueue = dispatch_get_main_queue()
let dispatch_duration = dispatch_time(DISPATCH_TIME_NOW, Int64(duration * Double(NSEC_PER_SEC)))
/* See Grand Central Dispatch Reference for note on NSEC_PER_SEC */
/* Push or pop controllers and the prompt will change to that
* controller’s prompt (default is nil). Tested iOS 8, 8.1 */
dispatch_after(dispatch_duration, mainQueue, {
self.navigationItem.prompt = nil
})
}
/* else {
* println("View controller cannot toast without a navigation controller")
* /* Debugging only. */
* } */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment