Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 7 UIBarButtonItem font changes when tapped

I'm attempting to change my UIBarButtonItem font. It looks good when ViewControllers load. But if I tap on the bar button, or swipe right as if to move to the previous ViewController (but then pull back to the current one), the font changes back to the system font. Here's what I'm setting in my AppDelegate:

NSDictionary* barButtonItemAttributes = @{NSFontAttributeName: [UIFont fontWithName:@"SourceSansPro-Light" size:20.0f]};
[[UIBarButtonItem appearance] setTitleTextAttributes: barButtonItemAttributes forState:UIControlStateNormal];
[[UIBarButtonItem appearance] setTitleTextAttributes: barButtonItemAttributes forState:UIControlStateHighlighted];
[[UIBarButtonItem appearance] setTitleTextAttributes: barButtonItemAttributes forState:UIControlStateSelected];
[[UIBarButtonItem appearance] setTitleTextAttributes: barButtonItemAttributes forState:UIControlStateDisabled];

And here's an example of my viewWillAppear:

- (void) viewWillAppear:(BOOL)animated {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(doneButtonPressed)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithRed:141.0/255.0 green:209.0/255.0 blue:205.0/255.0 alpha:1.0];
}

Am I somehow changing the font back, or am I misusing the appearance proxy?

like image 509
hodgesmr Avatar asked Feb 06 '14 00:02

hodgesmr


2 Answers

The problem is that the tintColor setting conflicts with the title text attributes. Comment out that line and all will be well.

If you are going to use title text attributes, then incorporate the text color into those attributes:

NSDictionary* barButtonItemAttributes =
@{NSFontAttributeName:
      [UIFont fontWithName:@"Georgia" size:20.0f],
  NSForegroundColorAttributeName:
      [UIColor colorWithRed:141.0/255.0 green:209.0/255.0 blue:205.0/255.0 alpha:1.0]  
 };
like image 174
matt Avatar answered Sep 28 '22 15:09

matt


By using this approach in viewDidLoad method you can set custom text,font,size etc all at once place.

UIView *customBarButtonView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 30)];

UIButton *buttonDone = [UIButton buttonWithType:UIButtonTypeSystem];
[buttonDone addTarget:self action:@selector(doneButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

buttonDone.frame = CGRectMake(10, 0, 50, 30);

buttonDone.titleLabel.textColor = [UIColor colorWithRed:141.0/255.0 green:209.0/255.0 blue:205.0/255.0 alpha:1.0];
buttonDone.titleLabel.font = [UIFont fontWithName:@"SourceSansPro-Light" size:20.0f];
[buttonDone setTitle:@"Done" forState:UIControlStateNormal];
[customBarButtonView addSubview:buttonDone];

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:customBarButtonView];
like image 24
bhavya kothari Avatar answered Sep 28 '22 15:09

bhavya kothari