Last active
September 29, 2017 12:42
-
-
Save danielt1263/f29fe1b33941b88b0793395b68beccac to your computer and use it in GitHub Desktop.
This file contains 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
enum UserInteractionError: Error { | |
case userCanceled | |
} | |
extension UIViewController | |
{ | |
func choiceIndexUsingActionSheet(title: String, message: String, choices: [String], onSourceView view: UIView) -> Promise<Int> { | |
return Promise(queue: DispatchQueue.main) { fulfill, reject in | |
let alert = UIAlertController(title: title.isEmpty ? nil : title, message: message.isEmpty ? nil : message, preferredStyle: .actionSheet) | |
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in reject(UserInteractionError.userCanceled) }) | |
let actions = choices.enumerated().map { offset, element in | |
UIAlertAction(title: element, style: .default, handler: { _ in fulfill(offset) }) | |
} | |
for action in actions + [cancelAction] { | |
alert.addAction(action) | |
} | |
if let popoverPresentationController = alert.popoverPresentationController { | |
popoverPresentationController.sourceView = view | |
popoverPresentationController.sourceRect = view.bounds | |
} | |
self.present(alert, animated: true, completion: nil) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment