Skip to content

Instantly share code, notes, and snippets.

@macneko-ayu
Last active July 5, 2021 10:36
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save macneko-ayu/3bcd1694c47c150ea0e36de4b8a18da4 to your computer and use it in GitHub Desktop.
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")
}
}
}
@lglam
Copy link

lglam commented Jul 5, 2021

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment