Confirm back button on UINavigationController

前端 未结 7 1849
南旧
南旧 2020-12-09 18:03

I am using the storyboard for my app which is using UINavigationController. I would like to add a confirmation dialog to the default back button so

相关标签:
7条回答
  • 2020-12-09 18:56

    Easy peasy. Just cover the button with a transparent UIControl and capture the touches.

    - (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
    
    #define COVER_HEIGHT    44
        //make this an iVar:  UIControl *backCover;
        if ( backCover == nil ) {
            CGRect cFrame = CGRectMake( 0, self.view.frame.origin.y-COVER_HEIGHT, 100, COVER_HEIGHT);
            backCover = [[UIControl alloc] initWithFrame:cFrame]; // cover the back button
            backCover.backgroundColor = [[UIColor orangeColor] colorWithAlphaComponent:0.2]; // transparent
            // use clearColor later
            [backCover addTarget:self action:@selector(backCoverAction:)
                forControlEvents:UIControlEventTouchDown];
            [self.view.window addSubview:backCover];
        }
    }
    
    - (void)viewWillDisappear:(BOOL)animated
    {
        [super viewWillDisappear:animated];
    
        [backCover removeFromSuperview]; // prevent coverage on another view
        backCover = nil;
    }
    
    - (void)backCoverAction:(UIControl *)sender
    {
        // decide what to do -- maybe show a dialog.
        // to actually go "Back" do this:
        [self.navigationController popViewControllerAnimated:YES]; // "Back"
    }
    

    This scheme also works for tabBar buttons, but it's more complex to determine the location.

    0 讨论(0)
提交回复
热议问题