Search code examples
iphoneipaduinavigationcontroller

Change navigation bar button text color


I am creating a custom view to generate navigation bar items.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        UIView *backButtonView = [[UIView alloc] initWithFrame:CGRectMake(0,0,70,35)];
        UIButton *myBackButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
        [myBackButton setFrame:CGRectMake(0,0,70,35)];
        myBackButton.titleLabel.text = @"Back";
        myBackButton.backgroundColor = [UIColor yellowColor];
        myBackButton.titleLabel.textAlignment = UITextAlignmentCenter;
        myBackButton.titleLabel.textColor = [UIColor blackColor];
        [myBackButton setEnabled:YES];
        [myBackButton addTarget:self.navigationController action:@selector(moveBack:) forControlEvents:UIControlEventTouchUpInside];
        [backButtonView addSubview:myBackButton];
        [myBackButton release];
        UIBarButtonItem* backButton = [[UIBarButtonItem alloc] initWithCustomView:backButtonView];
        self.navigationItem.leftBarButtonItem = backButton;
        [backButtonView release];
        [backButton release];


        CGRect frame = CGRectMake(300, 0, 400, 35);
        UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
        label.backgroundColor = [UIColor yellowColor];
        label.font = [UIFont boldSystemFontOfSize:20.0];
        label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        label.textAlignment = UITextAlignmentCenter;
        label.textColor = [UIColor blackColor];
        label.text = @"Order booking";
        self.navigationItem.titleView = label;
    }
    return self;
}  

With this I am having the following output :

enter image description here

I want the bar button to have same background color as navigation bar and its text in black color. I have tried doing it the either way by using UINavigationController delegate, but didn't get success. What changes do I need to make?


Solution

  • Read the 5.0 documentation. There was a WWDC '11 session on this very thing about a new, and much easier way, to do this. (Session 114 - Customizing the Appearance of UIKit Controls).