LoginSignup
0

More than 5 years have passed since last update.

UIAlertController生成を他クラスに切り分ける

Last updated at Posted at 2017-10-04

以下の内容だと汎用性がなく、切り分ける意味がなさそうなので、改めて書き直しました。

UIAlertController生成を他クラスに切り分ける PART2
https://qiita.com/d-kawahara/items/fab8ab91dfd2e79ef005

やってみたこと

普段からUIAlertControllerを使う際はコード量が多くなってしまっていたので、
今回、UIAlertControllerの生成を別クラスに切り出して使ってみました。

生成クラスの作成

@implementation AleartHelper

- (UIAlertController *)createNewAleartController {
    UIAlertController *newAleartController = [UIAlertController
                                              alertControllerWithTitle:@"タイトル"
                                              message:@"メッセージ"
                                              preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancelButton = [UIAlertAction
                                   actionWithTitle:@"キャンセル"
                                   style:UIAlertActionStyleDefault
                                   handler:^(UIAlertAction *action) {
                                       // 何かのアクション
                                   }];
    UIAlertAction *saveButton = [UIAlertAction
                                 actionWithTitle:@"保存"
                                 style:UIAlertActionStyleDefault
                                 handler:^(UIAlertAction *action) {
                                     // 何かのアクション
                                 }];

    [newAleartController addAction:cancelButton];
    [newAleartController addAction:saveButton];

    return newAleartController;
}
@end 

受け取りと表示

#import "ViewController.h"
#import "AleartHelper.h"

@interface ViewController ()
@property (weak, nonatomic) UIAlertController *aleartController;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    AleartHelper *aleartHelper = [[AleartHelper alloc]init];
    self.aleartController = [aleartHelper createNewAleartController];

}

- (IBAction)aleart:(id)sender {
    [self presentViewController:self.aleartController animated:YES completion:nil];
}

@end

まとめ

とりあえず切り分けてみましたが、アラートアクション結果の取得などを考えると、無理に切り分けなくても良いのかなと少し迷ってしまいました。
初歩的な知識ですが、備忘録として残しました。

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
0