-->

Change color of UIBarButtonSystemItemCancel

2019-08-26 03:28发布

问题:

If I use the UIBarButtonSystemItemCancel, it's color is set to that of the navigation bar. However, in the Photos App, the "Cancel" button is shown with a blue background. How can I also set the UIBarButtonSystemItemCancel to have a blue background please?

回答1:

your can use image as button image as

UIImage *buttonImage = [UIImage imageNamed:@"image.png"];

//create the button and assign the image
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];


//create a UIBarButtonItem with the button as a custom view
//UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];

[button addTarget:self action:@selector(clickActionItem:) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button ];




self.navigationItem.rightBarButtonItem = rightBarButtonItem;


回答2:

set the theNavigationController.navigationBar.barStyle to UIBarStyleBlackTranslucent

theNavigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;

and the buttons will be blue by default.



回答3:

There is a better way than using an image. The UISegmentedControl can be configured to look just like a UIBarButtonItem and UISegmentedControl has a tintColor property.

UISegmentedControl *button = [[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:itemTitle, nil]] autorelease];
    button.momentary = YES;
    button.segmentedControlStyle = UISegmentedControlStyleBar;
    button.tintColor = color;
    [button addTarget:theTarget action:selector forControlEvents:UIControlEventValueChanged];

    UIBarButtonItem *removeButton = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];

I built a UIBarButtonItem category that'll do this.