您也可以像這樣創建子類。首先我要去製作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:)];
}
我所有的代碼工作正常。希望它會幫助你。
來源
2012-11-13 15:28:29
IKQ
這就是我所做的......但這並不能解決UINavigationController後退按鈕或UITableViewController默認編輯按鈕等問題。 – VTS12
你必須在你的ViewController裏面調用這個函數。 self.navigationItem.rightBarButtonItem = [[CustomBarButtonItem sharedInstance] checkinButtonwithTarget:self andAction:@selector(revealMenu :)]; – IKQ
在哪個按鈕上對ViewController進行調用?我正在嘗試自定義UINavigationController上的後退按鈕... – VTS12