更改完成的UIBarButtonItem背景图像

时间:2012-01-18 20:46:12

标签: iphone uiimage uibarbuttonitem

我想制作一个自定义UIBarButtonItem来表示Done按钮。 我希望能够将应用程序国际化,因此我希望文本可以直接编辑。考虑到“完成”标签的不同长度,我设计了一个可伸缩的图像。是否可以直接更改默认编辑按钮背景或是否需要自定义UIBarButtonItem?如果是这样,根据标签的长度动态调整背景stretchchableImage的方法是什么?

2 个答案:

答案 0 :(得分:7)

如果您仅定位iOS 5.0,则可以使用新的UIAppearance方法-setBackButtonBackgroundImage:forState:barMetrics:专门更改默认外观。

如果您需要支持旧版本的iOS,则应该继承UIBarButtonItem,添加UIButton实例变量,创建它并在–initWithCustomView:方法中调用init你的UIBarButtonItem。这是因为UIBarButtonItem不是UIView的子类,您无法在其中绘制自定义图像。您还应手动设置width的{​​{1}}属性。

UIBarButtonItem

PS。不要忘记覆盖子类的@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 target属性以使用action实例。

答案 1 :(得分: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会自动将其宽度调整为标签的宽度。