UIBarButtonItem Highlighted Color
I have set a custom tint color for a UINavigationBar
(within a UINavigationController
) which, in turn, sets an appropriate matching color for the UIBarButtonItems
which are inserted into the UINavigationBar
. However, when I select a UIBarButtonItem
the button t开发者_运维技巧urns into (presumably) the highlighted state and presents a different color, which looks quite a bit out and does not nicely match the tint color. Is there a way to change this highlighted state color to a custom color?
Ideally, I would like to just create a category on UIBarButtonItem
which changes the highlighted color for all instances of UIBarButtonItem
, as this would avoid the need to explicitly subclass UIBarButtonItems
and then change every reference in my app to use the subclass (which will be tricky, as I am using some third-party libraries which just use UIBarButtonItem
and I don't want to go messing with their implementation).
Any help would be greatly appreciated.
From what I remember from facing a similar issue, UINavigationBar will just take the tintColor and make it darker for the UIBarButtonItem (unless the style is set to BarStyleBlack, in which case it makes it a dull gray).
To do what you ask, I would create a custom UIButton with background images for the different control states that match your color scheme, then use this UIButton as the view for a custom UIBarButtonItem.
UIButton *customButton = [UIButton buttonWithType:...];
//normal_button.png and selected_button.png need to be created by you
[customButton setBackgroundImage: [UIImage imageNamed:@"normal_button.png"] forState:UIControlStateNormal];
[customButton setBackgroundImage: [UIImage imageNamed:@"selected_button.png"] forState:UIControlStateSelected];
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView: customButton];
If you want to try and encapsulate this, you could always create a factory or a custom init method on UIBarButtonItem (via a category) and use the above code (with slight modifications).
I am aware that I am not fully addressing your second point on just overriding the control state with a category. I don't know what method to override in UIBarButtonItem to do such a thing, but you may be able to accomplish what you want via method swizzling (http://cocoadev.com/index.pl?MethodSwizzling) once you find out which method you want to exchange.
I should note that I've only ever used swizzling for testing/debugging.
If you're using Interface Builder, drag and drop an UIButton to the navigation's bar right side, and it gets in as a right navigation bar button item. Then, configure different tints for different states of the button, and you're done. Works in Xcode 10 and Swift 4.
精彩评论