2016-06-27 14 views
1

私はこのUIAlertControllerを、タイトルと内容の2つのパラメータを受け入れるユーティリティとして持っています。私は "確認"ボタンを変更したい。私はこのユーティリティを複製し、特定の機能を実行する別のパラメータを追加したい。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

私はどのように使用されるのか尋ねることはできますか?それのサンプル?ユーザーが[OK]をクリックしたときに何かを実行したいだけです。 – 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

関連する問題