[英]Changing Done UIBarButtonItem's background image
我想制作一个自定义UIBarButtonItem来表示“完成”按钮。 我希望能够对该应用程序进行国际化,因此我希望文本可以直接编辑。 为了考虑“ Done”标签的不同长度,我设计了一个StretchableImage。 是否可以直接更改默认的编辑按钮背景,还是需要自定义UIBarButtonItem? 如果是这样,将如何根据标签的长度动态调整背景StretchableImage的大小?
如果仅针对iOS 5.0,则可以使用新的UIAppearance
方法-setBackButtonBackgroundImage:forState:barMetrics:
专门更改默认外观。
如果您需要支持旧版本的iOS,你应该继承UIBarButtonItem
,添加一个UIButton
实例变量,创建并调用–initWithCustomView:
在init
的方法UIBarButtonItem
。 这是因为UIBarButtonItem
不是UIView
的子类,因此无法在其中绘制自定义图像。 您还应该手动设置UIBarButtonItem
的width
属性。
@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
PS。 不要忘记重写子类的target
和action
属性以使用button
实例。
我可能误解了您的问题,但是我相信您想要的只是:
UIBarButtonItem *btnDone = [[UIBarButtonItem alloc] initWithTitle:@"I am done" style:UIBarButtonItemStyleBordered target:self action:nil];
UIImage *stretchable = [[UIImage imageNamed:@"StretchableImage.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:16];
[btnDone setBackgroundImage:stretchable forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[self.navigationItem setRightBarButtonItem:btnDone];
UIBarButtonItem会自动将其宽度调整为标签的宽度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.