2016-06-27 7 views
1

У меня этот UIAlertController как утилита, которая принимает два пареметра, заголовок и содержимое. Я хочу изменить кнопку «подтвердить». Я хочу дублировать эту утилиту и добавить другой параметр, который выполнит определенную функцию.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]; 
+0

Не используйте функцию, используйте замыкающий (завершающий блок). – Wain

+0

Могу ли я спросить, как это используется? и образец его? Я просто хочу что-то выполнить, когда пользователь нажимает ОК. – EdBer

ответ

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]; 
+0

Пробовал первый метод, и он работал хорошо! Спасибо за ответ! :) – EdBer

+1

Рад помочь :) – KlimczakM

+1

@EdBer Рассмотрите возможность принятия ответа, если он соответствует вашим потребностям. – KlimczakM