在ios4自定义导航栏的返回按钮,实际上自定义了其 leftBarButtonItem,这里为了便于重用,我定义了一个类:
.h 文件
#import <UIKit/UIKit.h> @interface NavBackBarButtonItem : UIButton - (id)initWithTitle:(NSString *)title; @end
.m 文件
#import "NavBackBarButtonItem.h" @implementation NavBackBarButtonItem - (id)initWithTitle:(NSString *)title { self = [super init]; if (self) { UIImage *backBarBtn = [[UIImage imageNamed:@"backBarBtn"] stretchableImageWithLeftCapWidth:13.0 topCapHeight:0.0]; [self setBackgroundImage:backBarBtn forState:UIControlStateNormal]; UIFont *font = [UIFont systemFontOfSize:13.0f]; CGSize size = [title sizeWithFont:font]; self.frame = CGRectMake(0, 0, size.width + backBarBtn.size.width, backBarBtn.size.height); UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(13, 0, size.width + backBarBtn.size.width - 13, backBarBtn.size.height)]; titleLabel.text = title; titleLabel.font = font; titleLabel.backgroundColor = [UIColor clearColor]; titleLabel.textColor = [UIColor whiteColor]; [self addSubview:titleLabel]; [titleLabel release]; } return self; } @end
popViewController 函数是返回按钮的响应事件
- (void)popViewController { [self.navigationController popViewControllerAnimated:YES]; }
UINavigationItem *item = [self.navigationController.navigationBar.items lastObject]; UIButton *backBtn = [[NavBackBarButtonItem alloc] initWithTitle:item.title]; [backBtn addTarget:self action:@selector(popViewController) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithCustomView:backBtn]; self.navigationItem.leftBarButtonItem = backBarButton; [backBtn release]; [backBarButton release];
在ios5下,自定义返回按钮比较简单。比如,viewController1 pushViewController 了 viewController2,现在需要自定义viewController2的返回按钮,只需要在viewController1的文件里加入如下代码:
UIBarButtonItem *bbtn = [[UIBarButtonItem alloc] initWithTitle:self.navigationItem.title style:UIBarButtonItemStyleBordered target:nil action:nil]; UIImage *backBarBtn = [[UIImage imageNamed:@"backBarBtn"] resizableImageWithCapInsets:UIEdgeInsetsMake(0.0, 13.0, 0.0, 5.0)]; [bbtn setBackButtonBackgroundImage:backBarBtn forState:UIControlStateNormal barMetrics:UIBarMetricsDefault]; self.navigationItem.backBarButtonItem = bbtn; [bbtn release];