Is there an easy way to change the text color of a

2019-04-17 00:38发布

Is there an easy way to change the text color of a UIBarButtonItem without using an UIImage as the background?

By default the text is always white. I'd like to make it black.

4条回答
Deceive 欺骗
2楼-- · 2019-04-17 00:56

The direct answer to your question is no.

You can't simply change the color of a UIBarButtonItem by setting one of its properties. You can set the tintColor property of the UIToolBar or UINavigationBar that contains the UIBarButtonItems, but that also affects the color of the toolbar itself and doesn't offer too much customization.

If that doesn't work for you, a custom view as the other answers suggest is a fine idea.

Good luck!

查看更多
家丑人穷心不美
3楼-- · 2019-04-17 00:58

I'd rather use a UIButton inside a UIBarButtonItem and customize that one.

This is an example with custom graphics for a custom UIButton. The idea stays the same use initWithCustomView of the UIBarButtonItem to put something else in it which is easily customizable.

self.closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
[closeButton setImage:[UIImage imageNamed:@"webview_close_button_normal.png"] forState:UIControlStateNormal];
[closeButton setImage:[UIImage imageNamed:@"webview_close_button_pressed.png"] forState:UIControlStateHighlighted];
closeButton.frame = CGRectMake(0, 0, 121, 36);
[closeButton addTarget:self action:@selector(closeAdViewController) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem * aBarButtonAdClose = [[[UIBarButtonItem alloc] initWithCustomView:closeButton] autorelease];
查看更多
beautiful°
4楼-- · 2019-04-17 01:04

Thank to IOS 5.0 you do not need to use images for that.You can set various text attributes with following code.

UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:@"Title"     style:UIBarButtonItemStyleBordered target:nil action:nil];

if ([button respondsToSelector:@selector(setTitleTextAttributes:forState:)]) {

    NSDictionary *textAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                               kTextColor,UITextAttributeTextColor,
                                               nil];

    [[UIBarButtonItem appearance] setTitleTextAttributes:textAttributes                   
                                  forState:UIControlStateNormal];

}
查看更多
劳资没心,怎么记你
5楼-- · 2019-04-17 01:11

You can set a custom view by using

[[UIBarButtonItem alloc] - (id)initWithCustomView:(UIView *)customView]

查看更多
登录 后发表回答