开发者

UIBarButtonItem tintColor with UINavigationController

I have a navigation controller with 2 UIBarButtonItems in my navigation bar. I want to change the tint color only for the one on the right. I have found a way in static to do that:

[[self.navigationController.navigationBar.subviews objectAtIndex:2] setTintColor:[UIColor redColor]];

The problem is when I push a controller into my navigation controller to display another view, when I come back to the root view where my right navigation bar button is supposed to have a custom color, the color of the button is back to its default. And when I click again on it, the app crashes. It says it cannot change the tint color, like if the index for this element in my navigation bar changed.

I have tried other technics found on the internet, but they all failed when I use the navigation controller and come back to the root controller...

Any idea? Thanks!

Edit 1:

I would like a bordere开发者_StackOverflow中文版d style button in my UINavigationBar, with a red or green background color.

Regarding the other ways I found, it is pretty much a foreach loop of the views in the navigation bar, and if the view's kind of class is a button item then change the tintColor. It doesn't crash but it applies to all the UIBarButtonItem of my navigation bar (and I just want a specific button, the right one, not all of them). For example this tutorial is half working, my app crashes when coming back to the root view controller.


Digging into the subviews of the navigationcontroller.navigation bar wont fly with Apple, ...
the correct way to change the color of a UIBarButtonItem is to use a customView with the buttonitem. here is a link that explains...

UIBarButtonItem with color?


You simply create a segmented control with just one segment. Set its tint color as you like. You may also want to set its mode to momentary so it optically behaves like a button. Add the segmented control to the bar button item by using the initWithCustomView: initializer. That's how you typically create custom tinted buttons.

Example:

UISegmentedControl *cartControl = [[UISegmentedControl alloc] initWithFrame:CGRectMake(10,7,60,30)];
[cartControl setTintColor:[UIColor colorWithRed:0.35 green:0.47 blue:0.65 alpha:1]];
[cartControl addTarget:self action:@selector(cart:) forControlEvents:UIControlEventValueChanged];
[cartControl setSegmentedControlStyle:UISegmentedControlStyleBar]; 
[cartControl insertSegmentWithImage:[UIImage imageNamed:@"shopping_cart_white_small.png"] atIndex:0 animated:NO]; 
[cartControl setMomentary:YES];  

UIBarButtonItem *cartButton = [[UIBarButtonItem alloc] initWithCustomView:cartControl];
[cartControl release];
[[self navigationItem] setRightBarButtonItem:cartButton];
[cartButton release];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜