我想制作一个自定义的UIBarButtonItem来表示完成按钮。 我想使应用程序国际化,所以我希望文本可以直接编辑。要考虑“完成”标签的不同长度,我设计了一个StretchableImage。是否有可能直接更改默认的编辑按钮背景或是需要自定义的UIBarButtonItem?如果是这样,根据标签长度动态调整背景拉伸图片大小的方法是什么?更改完成UIBarButtonItem的背景图像
1
A
回答
7
如果您仅针对iOS 5.0,则可以使用新的UIAppearance
方法更改默认外观,具体为-setBackButtonBackgroundImage:forState:barMetrics:
。
如果您需要支持旧版本的iOS,你应该继承UIBarButtonItem
,加UIButton
实例变量,创建并在UIBarButtonItem
的init
方法调用–initWithCustomView:
。这是因为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
实例配合使用。
2
我可能误解了你的问题,但我相信所有你想要的是这样的:
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并自动调整它的宽度与标签的宽度。
+0
@Stanislav Yaglo是对的。此解决方案仅适用于iOS 5.如果您要定位旧版本,则需要制作UIBarButtonItem的简单子类。 – simonbs 2012-01-18 21:04:40
如何根据文字的宽度来调整按钮大小。另外,你如何将背景设置为StretchableImage?谢谢。 – 2012-01-18 21:15:39
您可以使用'NSString'的'-sizeWithFont:'方法:http://developer.apple.com/library/ios/#documentation/uikit/reference/NSString_UIKit_Additions/Reference/Reference.html。背景是用'UIButton'的'-setBackgroundImage:forState:'设置的。 – 2012-01-18 21:19:59
@ibeitia,我为你更新了代码。 – 2012-01-18 21:46:38