一。自定义navigationbar
- (void)initNavigationBar{ [self.navigationController setNavigationBarHidden:YES]; UINavigationBar *bar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 32)]; [bar setBackgroundImage:[UIImage imageNamed:@"zhuche_bar2.png"] forBarMetrics:UIBarMetricsDefault]; UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:nil]; UIButton *left = [UIButton buttonWithType:UIButtonTypeCustom]; [left setFrame:CGRectMake(0, 2, 28, 28)]; [left setImage:[UIImage imageNamed:@"zhuche_back.png"] forState:UIControlStateNormal]; [left addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:left]; [item setLeftBarButtonItem:leftButton]; [bar pushNavigationItem:item animated:NO]; [self.view addSubview:bar]; } - (void)back{ [self.navigationController popViewControllerAnimated:YES]; }
虽然可以解决自定义navigationbar的问题,左右按钮都可以替换,但是如果放在UITableViewController中,自定义的navigationbar会随着scrollview的滑动而滑动,不会像系统自带的navigationbar一样始终保持在屏幕最上方。那么我们可以有第二种解决方式,修改原来的navigationbar,其实就是改一下leftBarButtonItem或者rightBarButtonItem在navigationbar上面的位置:修改UIBarButtonItem 的边距。
二。修改UIBarButtonItem 的边距
@interface UINavigationItem (margin) @end @implementation UINavigationItem (margin) #if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1 - (void)setLeftBarButtonItem:(UIBarButtonItem *)_leftBarButtonItem { if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) { UIBarButtonItem *negativeSeperator = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]; negativeSeperator.width = -16;//此处修改到边界的距离,请自行测试 if (_leftBarButtonItem) { [self setLeftBarButtonItems:@[negativeSeperator, _leftBarButtonItem]]; } else { [self setLeftBarButtonItems:@[negativeSeperator]]; } } else { [self setLeftBarButtonItem:_leftBarButtonItem animated:NO]; } } - (void)setRightBarButtonItem:(UIBarButtonItem *)_rightBarButtonItem { if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) { UIBarButtonItem *negativeSeperator = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]; negativeSeperator.width = -12;//此处修改到边界的距离,请自行测试 if (_rightBarButtonItem) { [self setRightBarButtonItems:@[negativeSeperator, _rightBarButtonItem]]; } else { [self setRightBarButtonItems:@[negativeSeperator]]; } } else { [self setRightBarButtonItem:_rightBarButtonItem animated:NO]; } } #endif @end
以上代码可以放置在主视图控制器的.m文件里面,@implementation ViewController的上面
© 著作权归作者所有
文章评论(0)