Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample calling a delegate method like UIAlertView when UIAlertController's UIAlertAction is executed. Available with Swift and Objective-C.
import UIKit
@objc protocol AlertControllerDelegate: class {
func alertController(_ alert: UIAlertController, tappedIndex: Int) -> Void
}
private var DelegateKey: UInt8 = 0
private var TagKey: UInt8 = 0
extension UIAlertController {
func setDelegate(_ delegate: AlertControllerDelegate?) {
objc_setAssociatedObject(self, &DelegateKey, delegate, .OBJC_ASSOCIATION_RETAIN)
}
func getDelegate() -> AlertControllerDelegate? {
guard let object = objc_getAssociatedObject(self, &DelegateKey) as? AlertControllerDelegate else {
return nil
}
return object
}
func setTag(_ tag: Int) {
objc_setAssociatedObject(self, &TagKey, tag, .OBJC_ASSOCIATION_RETAIN)
}
func getTag() -> Int {
guard let object = objc_getAssociatedObject(self, &TagKey) as? Int else {
return 0
}
return object
}
func addAction(title: String, style: UIAlertActionStyle = .default, index: Int) {
addAction(UIAlertAction(title: title, style: style, handler: { (action) in
self.getDelegate()?.alertController(self, tappedIndex: index)
self.setDelegate(nil)
}))
}
}
@interface ViewController () <AlertControllerDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"title" message:@"message" preferredStyle:UIAlertControllerStyleAlert];
[alert setDelegate:self];
[alert setTag:3];
[alert addActionWithTitle:@"OK" style:UIAlertActionStyleDefault index:5];
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
}
- (void)alertController:(UIAlertController * _Nonnull)alert tappedIndex:(NSInteger)tappedIndex {
if ([alert getTag] == 3 && tappedIndex == 5) {
NSLog(@"fuga");
}
}
@end
class ViewController: UIViewController, AlertControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let alert = UIAlertController(title: "title", message: "message", preferredStyle: .alert)
alert.setDelegate(self)
alert.setTag(5)
alert.addAction(title: "OK", index: 3)
present(alert, animated: true, completion: nil)
}
func alertController(_ alert: UIAlertController, tappedIndex: Int) {
if alert.getTag() == 5 && tappedIndex == 3 {
print("hoge")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.