三个导航栏Item的区别(leftBarButtonItem/backBarButtonItem/backItem)

三种导航栏Item为:
1、self.navigationItem.leftBarButtonItem
2、self.navigationItem.backBarButtonItem
3、self.navigationController.navigationBar.backItem
其中UINavigationItem有三种:backBarButtonItemleftBarButtonItemrightBarButtonItem

一、leftBarButtonItem
如果设置了leftBarButtonItem,会替换掉backBarButtonItem。但可以设置leftItemsSupplementBackButtonYES,来同时显示leftBarButtonItembackBarButtonItem

leftBarButtonItem的自定义方式如下:


UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[backBtn setTitleColor:[UIColor colorWithRed:74 / 255.0 green:74 / 255.0 blue:74 / 255.0 alpha:1.0] forState:UIControlStateNormal];
[backBtn setTitle:@"  返回" forState:UIControlStateNormal];
[backBtn setImage:[UIImage imageNamed:@"NewBackButton"] forState:UIControlStateNormal];
[backBtn addTarget:self action:@selector(popViewController:) forControlEvents:UIControlEventTouchUpInside];
[backBtn sizeToFit];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];

- (void)popViewController:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

二、backBarButtonItem
backBarButtonItem是返回按钮,可以自定义。注意:假如想实现第二个ViewControllerbackBarButtonItem,就要先在第一个ViewController中设置backBarButtonItem

返回按钮backBarButtonItem的自定义方式如下:


UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] init];
[backBarButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:74 / 255.0 green:74 / 255.0 blue:74 / 255.0 alpha:1.0], NSFontAttributeName:[UIFont systemFontOfSize:18]} forState:UIControlStateNormal];
backBarButtonItem.title = [NSString stringWithFormat:@"返回"];
backBarButtonItem.image = [UIImage imageNamed:@"NewBackButton"];
self.navigationItem.backBarButtonItem = backBarButtonItem;

这样才会在第二个ViewController中有效果出现,显示返回按钮样式;​否则,无设置效果。

三、backItem
backItem只是一个只读属性,不能设置。

你可能感兴趣的:(三个导航栏Item的区别(leftBarButtonItem/backBarButtonItem/backItem))