導航控制器是一個非常常用的控制器,它能夠實現不同窗口的跳轉關系,能夠很好的描述控制器的層級關系.
從UIWindow創建控制器
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
//創建UIWindow
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
//創建控制器
ViewController *vc = [[ViewController alloc] init];
//設置控制器背景色
vc.view.backgroundColor = [UIColor redColor];
//創建導航控制器并設置vc為導航控制器的跟控制器
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
//設置導航控制器為UIWindow的跟控制器
self.window.rootViewController = nav;
//顯示window
[self.window makeKeyAndVisible];
return YES;
}
從storyboard創建
1.將storyboard中的控制器刪掉
2.找到UINavigationController,拖入storyboard中,如果不需要UITableView,可以將其刪掉,換成需要的控制器,然后從UINavigationController拖線至所添加控制器,設置其為跟控制器即可.
UINavigationController常用屬性
//標題欄文字
@property(nullable, nonatomic,copy) NSString *title;
//標題欄圖片
@property(nullable, nonatomic,strong) UIView *titleView;
//返回BarButtonItem
@property(nullable,nonatomic,strong) UIBarButtonItem *backBarButtonItem
//左邊BarButtonItem
@property(nullable, nonatomic,strong) UIBarButtonItem *leftBarButtonItem;
//右邊BarButtonItem
@property(nullable, nonatomic,strong) UIBarButtonItem *rightBarButtonItem;
//設置導航欄標題
self.title = @"打我啊魂淡!";
//創建圖片
UIImage *image = [UIImage imageNamed:@"men"];
//設置圖片永不渲染
image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//設置右邊,action可以監聽點擊事件
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStyleDone target:self action:nil];
//設置左邊,action可以監聽點擊事件
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:nil];
效果圖:
效果圖
segue(發音:segui)
segue是控制器跳轉的一個重要連接屬性,在導航控制器中應用非常廣泛.
segue有一個屬性:identfier(標識),在使用storyboard時,可通過identfier快速找到你要跳轉的控制器.segue有兩個非常常用的方法:
//執行sugue的identfier為(NSString *)的連接,創建并加載指定控制器
- (void)performSegueWithIdentifier:(NSString *)identifier sender:(nullable id)sender;
//準備執行Segue,從UIStoryboardSegue創建指定Segue連接
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender;
一般使用中,使用performSegueWithIdentifier:跳轉到指定控制器.該方法會創建通過identfier創建指定類型的控制器,然后加載.
prepareForSegue:方法底層會將當前控制器設置為segue的sourceViewController,需要跳轉的指定控制器為destinationViewController.在這個方法中可以用來與目標控制器傳值.