UIBarButtonItem with color?

2020-01-23 05:33发布

Is it possible to have a red UIBarButtonItem?

11条回答
神经病院院长
2楼-- · 2020-01-23 05:54

If anyone is looking for code to exactly duplicate a simple UIBarButtonItem:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[UIImage imageNamed:@"delete.png"] forState:UIControlStateNormal];
[button setTitle:@"Delete" forState:UIControlStateNormal];
button.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12.0f];
[button.layer setCornerRadius:4.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(batchDelete) forControlEvents:UIControlEventTouchUpInside];

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

And delete.png is:

delete.png

查看更多
该账号已被封号
3楼-- · 2020-01-23 05:56

You can create a custom image for the button and use that. Else, if you have set the tintColor of your navbar or toolbar to red, the button items on these will also appear red.

查看更多
何必那么认真
4楼-- · 2020-01-23 06:01

If using IB (Interface Builder), drag a UIView from the Library onto the UIToolBar, and it will generate a UIBarButtonItem with a custom view. You can then add any other controls you want to it, e.g. UIButton, UILabel, UIActivityIndicatorView.

查看更多
萌系小妹纸
5楼-- · 2020-01-23 06:05

When you have UIBarButtonItem setup in a Storyboard, you have to set the tintColor in the viewWillAppear() or viewDidAppear() method (putting it in viewDidLoad() doesn't work for me...):

- (void)viewWillAppear {
    [super viewWillAppear];
    [[self editButtonItem] setTintColor:[UIColor redColor]];
}

Or in Swift:

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    editButtonItem.tintColor = UIColor.redColor()
}

Note: tested on iOS 8/9.

查看更多
仙女界的扛把子
6楼-- · 2020-01-23 06:06

Using a custom image doesn't work as it just uses the alpha to render the button.

查看更多
不美不萌又怎样
7楼-- · 2020-01-23 06:09

You can set the tintColor property of a UIBarButtonItem in iOS 5. If you need to support iOS 4, check out this blog post. It details using a UISegmentedControl styled to look like a single button.

查看更多
登录 后发表回答