有没有办法在不使用UIApperance的情况下自定义所有uibarbuttonitems以获得背景图像?不幸的是我们的代码库有一些限制,我们无法使用UIAppearance所以我正在寻找替代方案。
提前致谢。
编辑:我能够通过继承UIBarButtonItem来实现这一点,并且它适用于我的大多数按钮...但我特别想知道如何使用UITableView编辑按钮和UINavigationController背景按钮等默认按钮来实现它。谢谢!
答案 0 :(得分:2)
您也可以像这样制作子类。首先,我去创建UIBarButtonItem的子类。我的CustomBarButtonItem.h应该是这样的。
@interface CustomBarButtonItem : UIBarButtonItem
+ (CustomBarButtonItem *)sharedInstance;
- (UIBarButtonItem *)backButtonwithTarget:(id)target andAction:(SEL)action;
@end
然后在我的CustomBarButtonItem.m里面应该这样。
@implementation CustomBarButtonItem
static CustomBarButtonItem * _sharedInstance = nil;
+ (CustomBarButtonItem *)sharedInstance
{
if (_sharedInstance != nil)
{
return _sharedInstance;
}
_sharedInstance = [[CustomBarButtonItem alloc] init];
return _sharedInstance;
}
- (UIBarButtonItem *)backButtonwithTarget:(id)target andAction:(SEL)action
{
UIImage *backImage = [UIImage imageNamed:@"back_btn_normal.png"];
UIImage *backPressed = [UIImage imageNamed:@"back_btn_hilight.png"];
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
[backButton setBackgroundImage:backImage forState:UIControlStateNormal];
[backButton setBackgroundImage:backPressed forState:UIControlStateHighlighted];
const CGFloat BarButtonOffset = 5.0f;
[backButton setFrame:CGRectMake(BarButtonOffset, 0, backImage.size.width, backImage.size.height)];
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, backImage.size.width, backImage.size.height)];
[containerView addSubview:backButton];
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:containerView];
return item;
}
@end
然后你想在哪里制作自定义NavigationItem(导航栏中的按钮),你可以为我自定义下面的代码。
- (void)viewDidLoad
{
self.navigationItem.leftBarButtonItem = [[CustomBarButtonItem sharedInstance] backButtonwithTarget:self andAction:@selector(searchButtonTapped:)];
}
我的所有代码都运行良好。希望它会对你有所帮助。
答案 1 :(得分:0)
_leftBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:[self imageButton]]
style:UIBarButtonItemStyleBordered
target:self
action:@selector(showLeftViewController)];
[navController.navigationBar.topItem setLeftBarButtonItem:_leftBarButton];
答案 2 :(得分:0)
要执行此操作:在 UINavigationBar 上创建类别并覆盖方法 drawRect
@implementation UINavigationBar (CustomBackground)
- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed: @"background"];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end
此代码允许您更改项目中所有UINavigationBar的背景。