Search code examples
ios7customizationbackbarbuttonitem

How to make a custom UIBarButton for Left Bar Button for BackBarButton


I am trying to customize UI of an application for iOS 7. I want exactly BackBarButton of iOS 7 but with different color for both arrow and title and different font for title. This is iOS 7 back button.

BackBarButton of iOS 7

I tried to customize it with following code

    UIImage *backButtonImage = [UIImage imageNamed:@"back.png"];
    UIButton *customBackButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [customBackButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [customBackButton setBackgroundImage:backButtonImage forState:UIControlStateNormal];
    [customBackButton setFrame:CGRectMake(0, 0, 30, 30)];       
    backButton = [[UIBarButtonItem alloc] initWithCustomView:customBackButton];
    [backButton setAction:@selector(backButtonPressed)];
    UIBarButtonItem * backButton = [[UIBarButtonItem alloc] initWithCustomView:customBackButton];

It seemed like this:

Customized BackBarButton

There is two problem with above Image.

First it is not aligned to left(iOS back button sticked to the left).

Second it doesn't have title of previous page.

I just added title attribute to custom button.

    [customBackButton setTitle:@"title" forState:UIControlStateNormal];

But it was like this:

customized backBarButton and it's title

How can I fix the problems(stick to left and title)?


Solution

  • I just found out how It is possible

    I wrote following code and it perfectly worked!

    UIBarButtonItem * backButton = [UIBarButtonItem new];
    UIView * backButtonView = [UIView new];
    [backButtonView setFrame:CGRectMake(0, 0, 90, 32)];
    
    UIImageView *backButtonImage = [UIImageView new];
    [backButtonImage setImage:[UIImage imageNamed:@"Setting/back.png"]];
    [backButtonImage setFrame:CGRectMake(-15, 0, 30, 30)];
    
    UILabel * backButtonLabel = [UILabel new];
    [backButtonLabel setFrame:CGRectMake(8, 0, backButtonView.frame.size.width, 30)];
    [backButtonLabel setBackgroundColor:[UIColor clearColor]];
    [backButtonLabel setTextColor:[UIColor whiteColor]];
    [backButtonLabel setTextAlignment:NSTextAlignmentLeft];
    [backButtonLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:18]];
    [backButtonLabel setText:title];
    
    UIButton *customBackButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [customBackButton addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [customBackButton setFrame:CGRectMake(0, 0, 90, 30)];
    
    [backButtonView addSubview:customBackButton];
    [backButtonView addSubview:backButtonImage];
    [backButtonView addSubview:backButtonLabel];
    
    backButton = [[UIBarButtonItem alloc] initWithCustomView:backButtonView];
    [backButton setAction:action];
    [self.navigationItem setLeftBarButtonItem:backButton animated:YES];