Make back button go to the previous view programmatically

前端 未结 3 1312
-上瘾入骨i
-上瘾入骨i 2021-02-20 13:20

I have a UIBarButtonItem and would like to programmatically set the action that goes to the previous controller (in my case, my previous view is a UITableViewController).

<
3条回答
  •  余生分开走
    2021-02-20 13:37

    Add following code in your controller, in - (void)viewDidLoad function:

    call [self addBackButtonWithTitle:@"back"]; if You want to custom backbutton with title.

    or [self addBackButtonWithImageName:@"back_button_image_name"]; if You want custom backbutton with image.

    /**
     *  @brief set lef bar button with custom title
     */
    - (void)addBackButtonWithTitle:(NSString *)title {
        UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:self action:@selector(backButtonPressed:)];
        self.navigationItem.leftBarButtonItem = backButton;
    }
    
    /**
     *  @brief set left bar button with custom image (or custom view)
     */
    - (void)addBackButtonWithImageName:(NSString *)imageName {
        // init your custom button, or your custom view
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        backButton.frame = CGRectMake(0, 0, 40, 22); // custom frame
        [backButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(backButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    
        // set left barButtonItem with custom view
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    }
    
    - (void)backButtonPressed:(id)sender {
        [self.navigationController popViewControllerAnimated:YES];
    }
    

提交回复
热议问题