IOS8 custom navigationbar and UIBarButtonItem margin
I. Custom 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];}
Although it can solve the problem of custom navigationbar, both the left and right buttons can be replaced, but if it is placed in UITableViewController, the custom navigationbar will slide with the scrollview, it is not always at the top of the screen like the built-in navigationbar. The second solution is to modify the original navigationbar to change the location of leftBarButtonItem or rightBarButtonItem on the navigationbar: Modify the margin of UIBarButtonItem.
II. Modify the margin of UIBarButtonItem
@ Interface UINavigationItem (margin) @ end @ implementation UINavigationItem (margin) # if _ parameters> _ IPHONE_6_1-(void) setLeftBarButtonItem :( UIBarButtonItem *) _ leftBarButtonItem {if ([[[UIDevice currentDevice] systemVersion] floatValue]> = 7.0) {UIBarButtonItem * negativeSeperator = [[UIBarButtonItem alloc] failed: Invalid target: nil action: nil]; negativeSeperator. width =-16; // the distance to the boundary. test if (_ leftBarButtonItem) {[self setLeftBarButtonItems: @ [negativeSeperator, _ leftBarButtonItem];} else {[self failed: @ [failed] ;}} else {[self setLeftBarButtonItem: _ leftBarButtonItem animated: NO] ;}}-(void) setRightBarButtonItem :( UIBarButtonItem *) _ rightBarButtonItem {if ([[[UIDevice currentDevice] systemVersion] floatValue]> = 7.0) {UIBarButtonItem * negativeSeperator = [[UIBarButtonItem alloc] failed: Invalid target: nil action: nil]; negativeSeperator. width =-12; // the distance to the boundary. test if (_ rightBarButtonItem) {[self setRightBarButtonItems: @ [negativeSeperator, _ rightBarButtonItem];} else {[self setRightBarButtonItems: @ [negativeSeperator] ;}} else {[self setRightBarButtonItem: _ rightBarButtonItem animated: NO] ;}# endif @ end
The above code can be placed in the. m file of the master View Controller, above @ implementation ViewController.