Iñi*_*tia 1 iphone uiimage uibarbuttonitem
我想创建一个自定义UIBarButtonItem来表示完成按钮.我希望能够将应用程序国际化,因此我希望文本可以直接编辑.考虑到"完成"标签的不同长度,我设计了一个可伸缩的图像.是否可以直接更改默认编辑按钮背景或是否需要自定义UIBarButtonItem?如果是这样,根据标签的长度动态调整背景stretchchableImage的方法是什么?
如果您仅定位iOS 5.0,则可以使用新UIAppearance方法更改默认外观-setBackButtonBackgroundImage:forState:barMetrics:.
如果你需要支持旧版本的iOS,你应该子类化UIBarButtonItem,添加一个UIButton实例变量,创建它并调用你–initWithCustomView:的init方法UIBarButtonItem.那是因为UIBarButtonItem它不是子类,UIView你不能在其中绘制自定义图像.您还应该手动设置width属性UIBarButtonItem.
@interface MYCustomBarButtonItem : UIBarButtonItem
{
UIButton *button;
}
- (id)initWithTitle:(NSString *)title; // name it in concordance with your needs
@end
#define kButtonHeight 30
#define kButtonTitleFontSize 12
#define kButtonTitlePadding 5
@implementation MYCustomBarButtonItem
- (id)initWithTitle:(NSString *)title
{
button = [UIButton buttonWithType:UIButtonTypeCustom]; // add retain here, and write the dealloc method if you aren't using ARC. Also, release it if self == nil.
self = [super initWithCustomView:button];
if (self) {
UIFont *titleFont = [UIFont boldSystemFontOfSize:kButtonTitleFontSize];
CGSize titleSize = [title sizeWithFont:titleFont];
CGFloat buttonWidth = titleSize.width + kButtonTitlePadding * 2;
button.frame = CGRectMake(0, 0, buttonWidth, kButtonHeight);
self.width = buttonWidth;
[button setTitle:title forState:UIControlStateNormal];
// Set your styles
button.titleLabel.font = titleFont;
// Normal state background
UIImage *backgroundImage = ...; // create your normal stretchable background image
[button setBackgroundImage:backgroundImage forState:UIControlStateNormal];
// Pressed state background
backgroundImage = ...; // create your pressed stretchable background image
[button setBackgroundImage:backgroundImage forState:UIControlStateHighlighted];
// and so on...
}
return self;
}
@end
Run Code Online (Sandbox Code Playgroud)
PS.不要忘了覆盖target和action你的子类的属性与你的工作button实例.