Search code examples
iosobjective-cuinavigationbaruibarbuttonitemuibarbuttonitemstyle

Add back arrow in UIBarButtonItem


I have this code which creates a UIBarButtonItem:

UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                               initWithTitle: @"ToDo"
                               style: UIBarButtonItemStyleBordered
                               target:self action: @selector(popToRoot:)];
[self.navigationItem setLeftBarButtonItem:backButton];

The issue is that removes the left arrow, and I would like to include that next to the text. How can I do that?

Thanks,

Peter


Solution

  • try this code

    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];  
    UIImage *backBtnImage = [UIImage imageNamed:@"BackBtn.png"]  ;  
    [backBtn setBackgroundImage:backBtnImage forState:UIControlStateNormal];  
    [backBtn addTarget:self action:@selector(goback) forControlEvents:UIControlEventTouchUpInside];  
    backBtn.frame = CGRectMake(0, 0, 54, 30);  
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:backBtn] ;  
    self.navigationItem.leftBarButtonItem = backButton;
    

    then define goback method like this

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

    Note: BackBtn.png will have ToDo text and back button image...

    Another way

    If you want to do without image, then add below code...

    -(void)viewWillAppear {
        self.title = @"Your Title"
    }
    
    -(void)viewWillDissapear {
        self.title = @"ToDo"
    }
    

    this will create ToDo when you goes to next view...