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

杀马特。学长 韩版系。学妹 提交于 2019-12-10 00:57:12

问题


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.


回答1:


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!




回答2:


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];

}



回答3:


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];



回答4:


You can set a custom view by using

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



来源:https://stackoverflow.com/questions/5652165/is-there-an-easy-way-to-change-the-text-color-of-a-uibarbuttonitem-without-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!