Created
March 2, 2017 04:17
-
-
Save wh1pch81n/b9fac46cfad678d0f6a08ee3419dc60b to your computer and use it in GitHub Desktop.
A helper method that will tap one of the buttons programmatically.
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
// Source: http://stackoverflow.com/a/40634752/3400034 | |
extension UIAlertController { | |
func tapButton(at index: Int, animated: Bool) { | |
guard Thread.isMainThread else { | |
DispatchQueue.main.async { | |
self.tapButton(at: index, animated: animated) | |
} | |
return | |
} | |
if (0 <= index) && (index < actions.count) | |
, let block = actions[index].value(forKey: "handler") | |
{ | |
typealias AlertHandler = @convention(block) (UIAlertAction) -> Void | |
let blockPtr = UnsafeRawPointer(Unmanaged<AnyObject>.passUnretained(block as AnyObject).toOpaque()) | |
let handler = unsafeBitCast(blockPtr, to: AlertHandler.self) | |
presentingViewController?.dismiss(animated: animated, completion: { [unowned self] in | |
handler(self.actions[index]) | |
}) | |
} | |
} | |
} | |
let alert = UIAlertController(title: "Hello", message: "world", preferredStyle: .alert) | |
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { (a: UIAlertAction) in | |
print("tappedAction") | |
})) | |
alert.tapButton(at: 0, animated: false) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment