我知道如何使用UIBarButtonItem
自定义-setBackgroundImage: forState: barMetrics:
,但我想为UIBarButtonItemStyleDone
和UIBarButtonItemStylePlain
使用不同的图片。
有没有办法使用UIAppearance
协议来实现这一目标?或者每次我想要一个“完成”样式按钮时我是否必须设置图像?
(我试着搞乱如下代码:
[[UIBarButtonItem appearance] setBackgroundImage:image forState:UIControlStateNormal barMetrics:UIBarButtonItemStyleDone];
但是,只需使用“完成”图像设置每个条形按钮。)
谢谢!
答案 0 :(得分:13)
在 iOS 6 中,您可以使用UIBarButtonItem类的新方法:
- (void)setBackgroundImage:(UIImage *)backgroundImage
forState:(UIControlState)state
style:(UIBarButtonItemStyle)style
barMetrics:(UIBarMetrics)barMetrics
它为指定的状态,样式和指标设置背景图像。 有关详细信息,请in the Apple docs
因此,要更改所有UIBarButtonItem的外观,您可以使用以下内容:
UIImage *doneBackgroundImage = [[UIImage imageNamed:@"button_done.png"]
resizableImageWithCapInsets:UIEdgeInsetsMake(0, 4, 0, 4)];
[[UIBarButtonItem appearance] setBackgroundImage:doneBackgroundImage
forState:UIControlStateNormal
style:UIBarButtonItemStyleDone
barMetrics:UIBarMetricsDefault];
答案 1 :(得分:10)
我找到的唯一方法是使用UIBarButtonItem类别: 的UIBarButtonItem + Appearance.h 的UIBarButtonItem + Appearance.m 希望这就是你要找的东西。
这个解决方案的功劳归于https://gist.github.com/2633081 #import <Foundation/Foundation.h>
@interface UIBarButtonItem (Appearance)
+ (void) setupAppearance;
@end
#import "UIBarButtonItem+Appearance.h"
#import <objc/runtime.h>
@implementation UIBarButtonItem (Appearance)
+ (void) setupAppearance {
[[UIBarButtonItem appearance] setBackgroundImage: [[UIImage imageNamed:@"customButton"]
resizableImageWithCapInsets: UIEdgeInsetsMake(8, 8, 8, 8)]
forState: UIControlStateNormal
barMetrics: UIBarMetricsDefault];
[[UIBarButtonItem appearance] setBackgroundImage: [[UIImage imageNamed:@"customButtonHiglhighted"]
resizableImageWithCapInsets: UIEdgeInsetsMake(8, 8, 8, 8)]
forState: UIControlStateHighlighted
barMetrics: UIBarMetricsDefault];
Class klass = objc_getClass("UIBarButtonItem");
Method targetMethod = class_getInstanceMethod(klass, @selector(setStyle:));
Method newMethod = class_getInstanceMethod(klass, @selector(__setStyle:));
method_exchangeImplementations(targetMethod, newMethod);
}
- (void) __setStyle:(UIBarButtonItemStyle)style {
[self __setStyle:style];
if(style == UIBarButtonItemStyleDone) {
[self setBackgroundImage:[[UIImage imageNamed:@"customDoneButton"] resizableImageWithCapInsets: UIEdgeInsetsMake(8, 8, 8, 8)]
forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[self setBackgroundImage:[UIImage imageNamed:@"customDoneButtonClicked"]
forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
} else {
[self setBackgroundImage:[[UIImage imageNamed:@"customButton"] resizableImageWithCapInsets: UIEdgeInsetsMake(8, 8, 8, 8)]
forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[self setBackgroundImage:[UIImage imageNamed:@"customButtonHighlighted"]
forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
}
}
@end