UIAlertController作为接受函数参数的实用程序

时间:2016-06-27 06:45:08

标签: ios objective-c uialertcontroller uialertaction

我将这个UIAlertController作为一个实用程序,接受两个参数,标题和内容。我想修改“确认”按钮。我想复制此实用程序并添加另一个将执行特定函数的参数。

-(UIAlertController *) modalWithTitle : (NSString *) title andContent: (NSString *) content{

    UIAlertController *alert = [UIAlertController alertControllerWithTitle: title message:content preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];

    [alert addAction:defaultAction];
    return alert;
}

示例代码:

UIAlertController *alert =[[ModalController alloc] modalWithTitle:@"Error" andContent:@"Network unavailable."
        andAction:<ENTER FUNCTION TO EXECUTE HERE>];
        [self presentViewController:alert animated:YES completion:nil];

1 个答案:

答案 0 :(得分:4)

你可以这样写:

+ (UIAlertController *)modalWithTitle:(NSString *)title andContent:(NSString *)content andHandler:(void (^)(UIAlertAction *))handler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle: title message:content preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:handler];
    [alert addAction:defaultAction];
    return alert;
}

用法:

void (^handler)(UIAlertAction *) = ^(UIAlertAction *action) {
    // code to execute
};
[[ModalController alloc] modalWithTitle:@"title" andContent:@"content" andHandler:handler];

另一种方法:

+ (UIAlertController *)modalWithTitle:(NSString *)title andContent:(NSString *)content andHandler:(void (^)(void))handler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:content preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        handler();
    }];
    [alert addAction:defaultAction];
    return alert;
}

用法:

void (^block)(void) = ^{
    // code to execute
};
[[ModalController alloc] modalWithTitle:@"title" andContent:@"content" andHandler:block];
相关问题