Created
September 30, 2016 07:28
-
-
Save JaleelNazir/7e206ea6f307561dca39e3d2224049e2 to your computer and use it in GitHub Desktop.
ask() - Show an OK/Cancel modal box that works in both iOS 7 and iOS 8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Show an OK/Cancel modal box that works in both iOS 7 and iOS 8 | |
func ask(title: String, #message: String, #completion: (answer: Bool) -> Void) { | |
if nil != objc_getClass("UIAlertController".UTF8String) { // use UIAlertController | |
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) | |
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action) -> Void in | |
completion(answer: false) | |
}) | |
let okayAction = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in | |
completion(answer: true) | |
}) | |
alertController.addAction(cancelAction) | |
alertController.addAction(okayAction) | |
UIApplication.topViewController()?.presentViewController(alertController, animated: true, completion: nil) | |
} | |
else { // use UIAlertView | |
let alertView = SelfDelegatingBoolAlertView(title: title, message: message, completion: completion) | |
alertView.show() | |
} | |
} | |
extension UIApplication { | |
class func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? { | |
if let nav = base as? UINavigationController { | |
return topViewController(base: nav.visibleViewController) | |
} | |
if let tab = base as? UITabBarController { | |
if let selected = tab.selectedViewController { | |
return topViewController(base: selected) | |
} | |
} | |
if let presented = base?.presentedViewController { | |
return topViewController(base: presented) | |
} | |
return base | |
} | |
} | |
class SelfDelegatingBoolAlertView: UIAlertView, UIAlertViewDelegate { | |
var completion: (answer: Bool) -> Void | |
init(title: String, message: String?, completion: (answer: Bool) -> Void) { | |
self.completion = completion | |
super.init(frame: CGRectZero) | |
self.delegate = self | |
self.title = title | |
self.message = message | |
addButtonWithTitle("Cancel") | |
addButtonWithTitle("OK") | |
cancelButtonIndex = 0 | |
} | |
required init(coder aDecoder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { | |
completion(answer: buttonIndex != alertView.cancelButtonIndex) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment