建议看此文之前,看如下文章
UINavigaiongController的基本使用
UINavigaiongController实现控制器直接的切换
**层次结构 **
@interface UINavigationController : UIViewController
@interface UIViewController (UINavigationControllerItem)
@interface UINavigationItem : NSObject <NSCoding>
@interface UISwitch : UIControl <NSCoding>
@interface UIControl : UIView
@interface UIBarButtonItem : UIBarItem <NSCoding>
@interface UIBarItem : NSObject <NSCoding, UIAppearance>
//UINavigationController的方法和属性
@property(nonatomic,readonly,strong) UINavigationItem *navigationItem;
//UINavigationItem的方法和属性
@property(nullable, nonatomic,strong) UIView *titleView;
@property(nullable, nonatomic,strong) UIBarButtonItem *leftBarButtonItem;
@property(nullable,nonatomic,copy)
NSArray<UIBarButtonItem *> *leftBarButtonItems
// UIBarButtonItem 的方法和属性
- (instancetype)initWithTitle:(nullable NSString *)title style
(UIBarButtonItemStyle)style target:
(nullable id)target action:(nullable SEL)action;
- (instancetype)initWithBarButtonSystemItem
(UIBarButtonSystemItem)systemItem target:
(nullable id)target action:(nullable SEL)action;
//系统的按钮,枚举
typedef NS_ENUM(NSInteger, UIBarButtonSystemItem) {. . .}
代码
- (void)viewDidLoad {
[super viewDidLoad];
//创建返回按钮
//当'返回按钮'和 title 同时设置时,栈顶界面,只显示'返回按钮'
UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithTitle:
@"返回按钮" style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.backBarButtonItem = backItem;
//创建中间标题文字
//self.navigationItem.title = @"这是个标题";
//创建中间标题视图
//self.navigationItem.titleView = [[UISwitch alloc]init];
//创建左侧按钮
UIBarButtonItem *lefItem2 = [[UIBarButtonItem alloc]initWithTitle:
@"左侧按钮" style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.leftBarButtonItem = lefItem2;
//创建系统的按钮
//target - 目标
//action - 事件
UIBarButtonItem *lefItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem : UIBarButtonSystemItemDone target:self
action:@selector(hehe)];
self.navigationItem.leftBarButtonItem = lefItem;
//创建左侧,多个按钮
self.navigationItem.leftBarButtonItems = @[lefItem,lefItem2];
//创建右侧按钮
//target: 目标
//action: 事件
UIBarButtonItem *rightItem =
[[UIBarButtonItem alloc]initWithTitle:@"右侧按钮"
style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.rightBarButtonItem = rightItem;
UIBarButtonItem *rightItem2 =
[[UIBarButtonItem alloc]initWithBarButtonSystemItem:
UIBarButtonSystemItemSearch target:self action:@selector(hehe)];
//创建右侧多个按钮
self.navigationItem.rightBarButtonItems =@[rightItem,rightItem2];
}
效果图
注意点
导航栏的内容,由栈顶控制器的navigationItem属性决定!