我试图使用 UIBarButtonItem 来显示图像和按钮,但我很确定它已被锁定以显示其中一个。使用这个线程的基本思想,我想出了一个使用 UIButton 和背景图像的解决方案。我所做的最大缺陷是,当标题文本的大小变化很大时,背景图像会拉伸,导致圆角看起来有点偏离。
CustomBarButtonItem.h
#import <UIKit/UIKit.h>
@interface CustomBarButtonItem : UIBarButtonItem {}
- (id) initWithImage:(UIImage *)image title:(NSString *)title target:(id)target action:(SEL)action;
@end
@interface UIBarButtonItem (CustomBarButtonItem)
+ (UIBarButtonItem *) barButtonItemWithImage:(UIImage *)image title:(NSString *)title target:(id)target action:(SEL)action;
@end
自定义栏按钮项.m
#import "CustomBarButtonItem.h"
@implementation CustomBarButtonItem
- (id) initWithImage:(UIImage *)image title:(NSString *)title target:(id)target action:(SEL)action {
UIButton *barButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIFont *font = [UIFont boldSystemFontOfSize:13];
barButton.titleLabel.font = font;
barButton.titleLabel.shadowOffset = CGSizeMake(0, -1);
barButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 5);
[barButton setImage:image forState:UIControlStateNormal];
[barButton setTitle:title forState:UIControlStateNormal];
[barButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[barButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
[barButton setTitleShadowColor:[[UIColor blackColor] colorWithAlphaComponent:0.5] forState:UIControlStateNormal];
[barButton setBackgroundImage:[UIImage imageNamed:@"bar-button-item-background.png"] forState:UIControlStateNormal];
barButton.frame = CGRectMake(0, 0, image.size.width + 15 + [title sizeWithFont:font].width, 30);
if (self = [super initWithCustomView:barButton]) {
self.target = target;
self.action = action;
}
return self;
}
@end
@implementation UIBarButtonItem (CustomBarButtonItem)
+ (UIBarButtonItem *) barButtonItemWithImage:(UIImage *)image title:(NSString *)title target:(id)target action:(SEL)action {
return [[[CustomBarButtonItem alloc] initWithImage:image title:title target:target action:action] autorelease];
}
@end
示例用法:
UIBarButtonItem *customButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"calendar.png"] title:@"Add to calendar" target:self action:@selector(addToCalendar)];
我的按钮背景图片是:
