LoginSignup
4
4

More than 5 years have passed since last update.

【Objective-C】UIAlertControllerを別クラスに分けて使い回す

Last updated at Posted at 2016-07-22

色んなとこで同じようなアラート出すことが稀によくあるので、AlertControllerを別クラスに分けて使い回す方法を少し調べてみました。
他にもカテゴリを使うなどやり方は色々あるみたいですが、これが一番簡単そうだったのでこのやり方でやってみました。

ソースコード

Util.h
@interface Util : NSObject
+ (void)dispOKAlert:(UIViewController*)viewController
   title:(NSString*)titleText
 message:(NSString*)messageText
  actionFunc:(void(^)(UIAlertAction *alertAction))actionFunc;
@end
Util.m
@implementation Util
+ (void)dispOKAlert:(UIViewController*)viewConrtroller
   title:(NSString*)titleText
 message:(NSString*)messageText
  actionFunc:(void(^)(UIAlertAction *alertAction))actionFunc
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:titleText
                                                                             message:messageText
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * alertAction =
    [UIAlertAction actionWithTitle:@"OK"
                             style:UIAlertActionStyleDefault
                           handler:actionFunc];
    [alertController addAction:alertAction];
    [viewController presentViewController:alertController animated:YES completion:nil];
}
@end
呼び出す方
[Util dispOKAlert:self title:@"Title" message:@"Message"
           actionFunc:^(UIAlertAction *alertAction){ 

/*OKボタンが押された時の処理*/

}];

今回はOKボタンだけのシンプルなものですが、
同じ感じでキャンセルボタン追加したり、styleを変えてActionSheetにしたりできます。

弁明

まだ始めたばかりで間違っている箇所があるかもしれません。
何か間違っている点があれば編集リクエスト等で指摘していただければ幸いです。

参考サイト

[Objective-C] UIAlertControllerをがんばってメソッドにしてみた: スタジオプリズム㐧3ブログ

4
4
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4