UIBarButtonItem color with backlight

I set a custom hue color for the UINavigationBar (within the UINavigationController ), which in turn sets the corresponding matching color for the UIBarButtonItems that are inserted into the UINavigationBar . However, when I select UIBarButtonItem , the button turns into a (presumably) selected state and represents a different color that looks very small and doesn’t match the hue color very well. Is there a way to change this highlighted state color to a custom color?

Ideally, I would just like to create a category on UIBarButtonItem that changes the highlighted color for all instances of UIBarButtonItem , as this will avoid an explicit subclass of UIBarButtonItems , and then change each link in my application to use a subclass (which will be difficult since I use some third-party libraries. which just use UIBarButtonItem , and I don't want to bother with their implementation).

Any help would be greatly appreciated.

+6
iphone cocoa-touch uikit uinavigationbar uibarbuttonitem
source share
2 answers

From what I remember, faced with a similar problem, the 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 gray gray).

To do what you ask, I would create a custom UIButton with background images for different control states that match your color scheme, and then use this UIButton as a view for the 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 can always create a factory or your own init method in UIBarButtonItem (through the category) and use the code above (with a few changes).

I know that I am not fully addressing your second question on simply redefining the management status with a category. I don’t know which method to override in UIBarButtonItem to accomplish such a thing, but you can accomplish what you want with the swizzling method (http://cocoadev.com/index.pl?MethodSwizzling) as soon as you find out which method you want to exchange.

I should note that I only ever used swizzling for testing / debugging.

0
source share

If you are using Interface Builder, drag the UIB button to the right side of the navigation bar and it will appear as an element of the right navigation bar button. Then set up different shades for different button states, and you're done. Works in Xcode 10 and Swift 4.

0
source share

All Articles