How to create uialertcontroller in global swift

后端 未结 12 1693
情深已故
情深已故 2020-12-05 12:09

I\'m trying to create uialertcontroller in Config.swift file as follow.

static func showAlertMessage(titleStr:String, messageStr:St         


        
12条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 12:49

    swift

    Here's what I used, this is the same as @penatheboss answered, just add the ability of adding actions and handlers.

    extension UIViewController {
        func popupAlert(title: String?, message: String?, actionTitles:[String?], actions:[((UIAlertAction) -> Void)?]) {
            let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
            for (index, title) in actionTitles.enumerated() {
                let action = UIAlertAction(title: title, style: .default, handler: actions[index])
                alert.addAction(action)
            }
            self.present(alert, animated: true, completion: nil)
        }
    }
    

    Just make sure actionTitles and actions array the same count. Pass nil if you don't need any action handler closure.

    self.popupAlert(title: "Title", message: " Oops, xxxx ", actionTitles: ["Option1","Option2","Option3"], actions:[{action1 in
    
    },{action2 in
    
    }, nil])
    

    Objective C:

    Add the category for UIViewController

    UIViewController+PopAlert.h

    #import 
    
    @interface UIViewController (UIViewControllerCategory)
    - (void) popAlertWithTitle: (NSString*) title message: (NSString*) message actionTitles:(NSArray *) actionTitles actions:(NSArray*)actions;
    @end
    

    UIViewController+PopAlert.m

    #import "UIViewController+PopAlert.h"
    
    @implementation UIViewController (UIViewControllerCategory)
    - (void) popAlertWithTitle: (NSString*) title message: (NSString*) message actionTitles:(NSArray *) actionTitles actions:(NSArray*)actions {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
        [actionTitles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UIAlertAction *action = [UIAlertAction actionWithTitle:obj style:UIAlertActionStyleDefault handler:actions[idx]];
            [alert addAction:action];
        }];
        [self presentViewController:alert animated:YES completion:nil];
    }
    @end
    

    Usage:

    #import UIViewController+PopAlert.h
    

    ...

    [super viewDidDisappear:animated];
        NSArray *actions = @[^(){NSLog(@"I am action1");}, ^(){NSLog(@"I am action2");}];
        [self popAlertWithTitle:@"I am title" message:@"good" actionTitles:@[@"good1", @"good2"] actions:actions];
    

提交回复
热议问题