LoginSignup
12

More than 5 years have passed since last update.

UINavigationBarの戻るボタンをカスタムしてスワイプで戻る挙動も有効にする

Posted at

UInavigationBarの戻るボタンをカスタムしつつ、スワイプで戻れるようにするには、以下のようにします。

戻るボタンをカスタムする
@interface HogeViewController ()

@property(nonatomic,weak) id orgDelegate;

@end

@implementation HogeViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if([[self.navigationController viewControllers] count] > 1){
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"NavigationLeftAllow"]
                                                                                 style:UIBarButtonItemStylePlain
                                                                                target:self
                                                                                action:@selector(actionPopViewController)];
        [self.navigationItem.leftBarButtonItem setBackgroundImage:[UIImage new]
                                                         forState:UIControlStateNormal
                                                       barMetrics:UIBarMetricsDefault];

        self.orgDelegate = self.navigationController.interactivePopGestureRecognizer.delegate;
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    self.navigationController.interactivePopGestureRecognizer.delegate = self.orgDelegate;
}

- (void)actionPopViewController
{
    [self.navigationController popViewControllerAnimated:YES];
}

スワイプのジェスチャーを受け取る部分の実装は微妙ですが、とりあえずこれで動作すると思います。

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
12