使用UIAppearance自定义UIBarButtonItem“完成”样式和“简单”样式
我知道如何使用-setBackgroundImage: forState: barMetrics:
来自定义UIBarButtonItem
,但是我想为UIBarButtonItemStyleDone
和UIBarButtonItemStylePlain
使用不同的图像。
有没有办法使用UIAppearance
协议来完成这个UIAppearance
? 或者我每次需要“完成”样式button时都必须设置图像?
(我试图用下面的代码搞乱:
[[UIBarButtonItem appearance] setBackgroundImage:image forState:UIControlStateNormal barMetrics:UIBarButtonItemStyleDone];
但是,这只是用“完成”图像设置每个栏button。)
谢谢!
在iOS 6中,您可以使用UIBarButtonItem类的新方法:
- (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state style:(UIBarButtonItemStyle)style barMetrics:(UIBarMetrics)barMetrics
它为指定的状态,样式和度量设置背景图像。 更多细节可以在Apple文档中find
所以要改变所有的UIBarButtonItems的外观,你可以使用如下的东西:
UIImage *doneBackgroundImage = [[UIImage imageNamed:@"button_done.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 4, 0, 4)]; [[UIBarButtonItem appearance] setBackgroundImage:doneBackgroundImage forState:UIControlStateNormal style:UIBarButtonItemStyleDone barMetrics:UIBarMetricsDefault];
对于IOS5 *
我发现唯一的方法是使用UIBarButtonItem类别:
的UIBarButtonItem + Appearance.h
#import <Foundation/Foundation.h> @interface UIBarButtonItem (Appearance) + (void) setupAppearance; @end
的UIBarButtonItem + Appearance.m
#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
希望这是你在找什么。 信用这个解决scheme去https://gist.github.com/2633081