LoginSignup
16
19

More than 5 years have passed since last update.

UINavigationControllerのpushViewControllerを少し便利に

Last updated at Posted at 2013-05-11

UINavigationControllerのpushViewController:animated:で画面遷移した場合、バックボタンの設定を以下のようにプッシュ元のViewControllerで設定してやる必要がありますよね。

UIViewControllerSubClass.m
UIBarButtonItem *back = [[[UIBarButtonItem alloc] initWithTitle:@"戻る"
                                                          style:UIBarButtonItemStyleBordered
                                                         target:nil
                                                         action:nil] autorelease];
[self.navigationItem setBackBarButtonItem:back];

iOS開発始めたばかりの人だとこれって結構ハマりポイントだったりしませんか?
それに画面遷移が多いアプリケーションだと毎回pushViewControllerする度にUIBarButtonItemを設定してやらないといけないですし。

ということでUIViewControllerをプッシュする際にわざわざUIBarButtonItemのインスタンスを自分で生成するのが面倒だと感じる場合はUINavigationControllerにカテゴリメソッドを追加してあげましょう。

UINavigationController+Push.h
@interface UINavigationController (Push)
- (void)pushViewController:(UIViewController *)viewController backButtonTitle:(NSString *)backTitle animated:(BOOL)animated;
@end
UINavigationController+Push.m
@implementation UINavigationController (Push)

- (void)pushViewController:(UIViewController *)viewController backButtonTitle:(NSString *)backTitle animated:(BOOL)animated
{
    UIBarButtonItem *back = [[[UIBarButtonItem alloc] initWithTitle:backTitle
                                                              style:UIBarButtonItemStyleBordered
                                                             target:nil
                                                             action:nil] autorelease];
    [self.visibleViewController.navigationItem setBackBarButtonItem:back];
    [self pushViewController:viewController animated:animated];
}

@end

こうすることで、プッシュ元のクラスでは以下のコードだけで画面の遷移・バックボタンの設定を行えます。

UIViewControllerSubClass
[self.navigationController pushViewController:viewController backButtonTitle:@"戻る" animated:YES];

この程度の拡張でも、画面遷移の多いアプリケーション開発では大いに役立つのではないでしょうか?

16
19
0

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
16
19