How to set custom UINavigationBarButton color

♀尐吖头ヾ 提交于 2019-12-24 16:10:03

问题


I'm trying to set a custom color for a button on my UINavigationBar, but only when a particular UIViewController is being displayed in it (I know this is dubious UI design, but it's a specific customer requirement).

Our current implementation uses a Swizzle to override drawRect for all UINavigationBar objects. This is necessary so our custom navigation bar colors are applied to standard iOS screens (like when adding a new contact through standard APIs).

I want to change the tint color of the navigation bar for one particular UIViewController to be different from the others, but the Swizzle always takes precedence.

I'm testing in the iOS 4.3 Simulator. We support iOS 3.x clients and above (iPhone, iPod and iPad), so I can't just use the newer iOS 5 APIs to customize it.

Other things I've tried, without success:

  • Adding setStyle calls (as per this workaround) to make the button update again.

  • I tried the UINavigationButton hack I found here (I know this is a private API and risks Apple rejecting the app). I tried putting that code in viewWillAppear as well.


回答1:


I think the answers to this question will answer yours. My answer, which uses a UISegmentedControl, doesn't require any private API calls.




回答2:


I got this to work by creating a UIButton with a custom background image, as per this Stackoverflow answer.

In case it helps anybody, here's my code:

#import <QuartzCore/QuartzCore.h>

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[UIImage imageNamed:@"mybackground.png"] forState:UIControlStateNormal];
[button setTitle:NSLocalizedString(@"Login", @"Button (9 chars limit) - Login") forState:UIControlStateNormal];
button.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12.0f];
[button.layer setCornerRadius:5.0f];
[button.layer setMasksToBounds:YES];
[button.layer setBorderWidth:1.0f];
[button.layer setBorderColor: [[UIColor grayColor] CGColor]];
button.frame=CGRectMake(0.0, 100.0, 60.0, 30.0);
[button addTarget:self action:@selector(myLoginActionMethod:) forControlEvents:UIControlEventTouchUpInside];

self._loginButton= [[UIBarButtonItem alloc] initWithCustomView:button]; 

In general, I think it is best to set the tint in the UIViewController like this (although in my case this doesn't work due to the drawRect swizzle being in place on the UINavigationBar in my code):

self.navigationController.navigationBar.tintColor=[UIColor blueColor];


来源:https://stackoverflow.com/questions/8220715/how-to-set-custom-uinavigationbarbutton-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!