[英]How can I change the background color of a UIBarButtonItem on iOS 7+?
[英]Change the background color of a UIBarButtonItem in ios 7
我有一個帶有正確UIBarButtonItem的UINavigationBar。
如何僅更改按鈕的背景顏色(而不是文本)?
UIBarButtonItem *postButton = [[UIBarButtonItem alloc] initWithTitle:@"POST" style:UIBarButtonItemStylePlain target:self action:@selector(postButtonPressed:)];
// Changes text color
postButton.tintColor = [UIColor blueColor];
如何更改背景顏色?
使用appearance
代理,
使用您喜歡的顏色創建1x1像素圖像。 在這種情況下,此圖像的名稱為“icons_gb.png”。 然后將以下代碼添加到AppDelegate.m
。 圖像顏色將在按鈕的背景中重復出現。
UIImage *btnBg = [[UIImage imageNamed:@"icons_bg"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
[[UIBarButtonItem appearance] setBackgroundImage:btnBg
forState:UIControlStateNormal
barMetrics:UIBarMetricsDefault];
你可以改變它:
yourNavigationBar.barTintColor = [UIColor yellowColor];
導航欄的顏色也會改變。
如果您只想更改UIBarButtonItem,請使用我的自定義類:
的UIBarButtonItem + Custom.h
#import <UIKit/UIKit.h>
@interface UIBarButtonItem (Custom)
+ (UIBarButtonItem *) barItemWithImage:(UIImage *)img size:(CGSize)size target:(id)target action:(SEL)selector;
@end
的UIBarButtonItem + Custom.m
#import "UIBarButtonItem+Custom.h"
@implementation UIBarButtonItem (Custom)
+ (UIBarButtonItem *) barItemWithImage:(UIImage *)img size:(CGSize)size target:(id)target action:(SEL)selector
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:img forState:UIControlStateNormal];
button.frame= CGRectMake(0.0, 0.0, size.width, size.height);
[button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *forward = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
return forward;
}
@end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.