开发者

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

Is there an easy way to change the text color of a UIBarButtonItem without using an UIImage as the bac开发者_运维技巧kground?

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


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

}


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


You can set a custom view by using

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


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜