本文介紹 UINavigationController
導(dǎo)航視圖控制器相關(guān)的常用方法懒棉。
1. 創(chuàng)建 UINavigationController
并設(shè)置為應(yīng)用窗口的根視圖控制器
初始化 UINavigationController
對(duì)象時(shí)卷谈,需要傳入 UIVIewController
實(shí)例對(duì)象的參數(shù)作為它的根視圖控制器遭居。再將 UINavigationController
對(duì)象設(shè)置為 UIWindow
應(yīng)用窗口對(duì)象的根視圖控制器而线。
在 Xcode 11 之前新創(chuàng)建的項(xiàng)目因宇,示例代碼如下:
/*
* 視圖控制器層級(jí)結(jié)構(gòu):
* UIWindow -> UINavigationController -> MainTableViewController
*
*/
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 設(shè)置和初始化應(yīng)用窗口的根視圖控制器
// 初始化應(yīng)用窗口
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// 創(chuàng)建主列表視圖控制器對(duì)象
MainTableViewController *mainTableViewController = [[MainTableViewController alloc] initWithStyle:UITableViewStylePlain];
// ??設(shè)置窗口根視圖控制器:UINavigationController
self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:mainTableViewController];
// 設(shè)置窗口背景色
self.window.backgroundColor = [UIColor whiteColor];
// 使窗口可見(jiàn)
[self.window makeKeyAndVisible];
// ??可選恤筛,全局設(shè)置窗口導(dǎo)航欄顏色、字體
[[UINavigationBar appearance] setBarTintColor:[UIColor orangeColor]];
[[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
return YES;
}
在 Xcode 11 之后創(chuàng)建的項(xiàng)目饶氏,因?yàn)?Apple 引入了 UIScene
特性讥耗,示例代碼如下:
// AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if (@available(iOS 13.0, *)) {
} else {
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
ViewController *con = [[ViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:con];
[self.window setBackgroundColor:[UIColor whiteColor]];
[self.window setRootViewController:nav];
[self.window makeKeyAndVisible];
}
return YES;
}
// SceneDelegate.m
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// 使用此方法可以有選擇地配置 UIWindow 窗口并將其附加到提供的 UIWindowScene 場(chǎng)景中。
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// 如果使用 storyboard疹启,window 屬性將會(huì)自動(dòng)初始化并附加到場(chǎng)景中
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// 該委托并不意味著連接場(chǎng)景或會(huì)話(huà)是新的(請(qǐng)參見(jiàn) `application:configurationForConnectingSceneSession`)
if (@available(iOS 13.0, *)) {
UIWindowScene *windowScene = (UIWindowScene *)scene;
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
[self.window setWindowScene:windowScene];
ViewController *con = [[ViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:con];
[self.window setBackgroundColor:[UIColor whiteColor]];
[self.window setRootViewController:nav];
[self.window makeKeyAndVisible];
}
}
2. 隱藏導(dǎo)航欄古程、工具欄
隱藏當(dāng)前視圖控制器頂部的導(dǎo)航欄:
[self.navigationController setNavigationBarHidden:YES];
隱藏當(dāng)前視圖控制器底部的工具欄:
[self.navigationController setToolbarHidden:YES];
使用場(chǎng)景
每當(dāng)進(jìn)入詳情頁(yè)面時(shí),隱藏頁(yè)面頂部的導(dǎo)航欄和頁(yè)面底部的工具欄喊崖,推出該詳情頁(yè)時(shí)(即返回到上一個(gè)頁(yè)面)籍琳,再顯示回頁(yè)面頂部的導(dǎo)航欄和工具欄。
#pragma mark - Lifecycle
// 每當(dāng)進(jìn)入此頁(yè)面時(shí)贷祈,隱藏頁(yè)面頂部的導(dǎo)航欄和頁(yè)面底部的工具欄
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.navigationController setNavigationBarHidden:YES];
[self.navigationController setToolbarHidden:YES];
}
// 每當(dāng)退出此頁(yè)面時(shí)趋急,不再隱藏頁(yè)面頂部的導(dǎo)航欄和頁(yè)面底部的工具欄
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.navigationController setNavigationBarHidden:NO];
[self.navigationController setToolbarHidden:NO];
}
3. 視圖入棧和出棧
3.1 推入下一個(gè)視圖控制器
- (void)pushToNextViewController {
// 實(shí)例化下一個(gè)視圖控制器
ViewController *secondViewController = [[ViewController alloc] initWithNibName:NSStringFromClass([ViewController class]) bundle:nil];
// 將該視圖控制器推入到導(dǎo)航視圖控制器中,相當(dāng)于入棧操作
[self.navigationController pushViewController:secondViewController animated:YES];
}
3.2 返回上一個(gè)視圖控制器
- (void)popToLastViewController {
// 當(dāng)前視圖控制器势誊,將從導(dǎo)航視圖控制器堆棧中移除呜达,并返回至上一個(gè)視圖控制器,相當(dāng)于出棧操作
[self.navigationController popViewControllerAnimated:YES];
}
3.3 根據(jù)索引返回到指定的視圖控制器
- (void)gotoIndexViewController {
// 根據(jù)導(dǎo)航視圖控制器中的全局序號(hào)粟耻,查找堆棧中指定序號(hào)的視圖控制器
UIViewController *viewController = [[self.navigationController viewControllers] objectAtIndex:2];
// 然后跳轉(zhuǎn)至該視圖控制器
[self.navigationController popToViewController:viewController animated:YES];
}
3.4 返回到指定的視圖控制器
通過(guò) for-in
循環(huán)遍歷 UINavigationController
的 viewControllers
數(shù)組查近,找到需要返回的視圖控制器頁(yè)面眉踱,然后將導(dǎo)航視圖控制器推出到該頁(yè)面上。
for (UIViewController *controller in self.navigationController.viewControllers) {
BOOL isKindOfClass = [controller isKindOfClass:[FisrtViewController class]];
if (isKindOfClass) {
[self.navigationController popToViewController:controller animated:YES];
}
}
3.5 返回到根視圖控制器
導(dǎo)航視圖控制器中的所有子視圖控制器霜威,都將全部出棧谈喳,從而跳轉(zhuǎn)到根視圖控制器。
- (void)popToRootViewController {
[self.navigationController popToRootViewControllerAnimated:YES];
}
4. 設(shè)置導(dǎo)航欄標(biāo)題戈泼、字體和顏色
self.navigationItem.title = @"首頁(yè)";
[self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.0f],NSForegroundColorAttributeName:ThemeColor}];
5. 導(dǎo)航欄相關(guān)屬性設(shè)置
- (void)setNavigationItemAttributes {
// 設(shè)置當(dāng)前視圖的導(dǎo)航欄標(biāo)題
self.navigationItem.title = @"首頁(yè)";
self.navigationController.navigationBar.hidden = NO;
// 設(shè)置頂部導(dǎo)航區(qū)的提示文字婿禽,prompt 屬性表示在導(dǎo)航欄按鈕上方顯示的說(shuō)明文字
// self.navigationItem.prompt = @"Loading";
// 設(shè)置導(dǎo)航欄背景是否透明
self.navigationController.navigationBar.translucent = NO;
// 設(shè)置導(dǎo)航欄系統(tǒng)樣式
// The navigation bar style that specifies its appearance.
self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
// 設(shè)置導(dǎo)航按鈕文本顏色,默認(rèn)藍(lán)色
// !!!: 此屬性設(shè)置的是全局導(dǎo)航欄里面的 item 項(xiàng)的顏色
// self.navigationController.navigationBar.tintColor = [UIColor greenColor];
}
6. 全局設(shè)置導(dǎo)航欄屬性
// 設(shè)置導(dǎo)航欄上的 item 的顏色
[[UINavigationBar appearance] setTintColor:ThemeColor];
// 設(shè)置導(dǎo)航欄的背景色
[[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
在 UINavigationBar
中大猛,與導(dǎo)航欄顏色設(shè)置相關(guān)的兩個(gè)屬性:
/**
tintColor 屬性作用于 navigation items 和 bar button items
@說(shuō)明:
1. tintColor 屬性的行為在 iOS 7.0 中發(fā)生了變化扭倾。它不會(huì)再影響導(dǎo)航欄的背景色。
2. tintColor 屬性的行為及其描述被添加到了 UIView 中挽绩。
3. 想要設(shè)置導(dǎo)航欄的背景顏色膛壹,請(qǐng)使用 barTintColor 屬性。
*/
@property(null_resettable, nonatomic,strong) UIColor *tintColor;
/**
barTintColor 屬性作用于 navigation bar background
注:除非將半透明屬性(translucent)設(shè)置為 NO唉堪,否則默認(rèn)情況下此顏色為半透明模聋。
*/
@property(nullable, nonatomic,strong) UIColor *barTintColor API_AVAILABLE(ios(7.0)) UI_APPEARANCE_SELECTOR; // default is nil
7. 刪除導(dǎo)航欄底部線(xiàn)條
[self.navigationController.navigationBar setShadowImage:[UIImage new]];
刪除導(dǎo)航欄底部線(xiàn)條,還有一個(gè)替代方法位于 Chameleon 框架中唠亚,該方法會(huì)把所有頁(yè)面的底部線(xiàn)條刪除:
self.navigationController.hidesNavigationBarHairline = YES;
8. 為導(dǎo)航欄右上角添加一個(gè)按鈕
導(dǎo)航欄 UINavigationBar
上的按鈕是 UIBarButtonItem
的實(shí)例链方。
#pragma mark - Lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
// 添加導(dǎo)航欄右側(cè)按鈕
[self addNavigationRightBarbutton];
}
#pragma mark - Private
- (void)addNavigationRightBarbutton {
// 設(shè)置當(dāng)前視圖右上角的導(dǎo)航欄按鈕標(biāo)題,以及按鈕點(diǎn)擊事件
UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"按鈕"
style:UIBarButtonItemStylePlain
target:self
action:@selector(rightBarButtonItemDidClicked:)];
self.navigationItem.rightBarButtonItem = rightBarButtonItem;
}
#pragma mark - IBActions
// 導(dǎo)航欄按鈕點(diǎn)擊事件方法
- (void)rightBarButtonItemDidClicked:(id)sender {
// ...
}
9. 自定義導(dǎo)航按鈕:左側(cè)按鈕趾撵、右側(cè)按鈕、中間標(biāo)題
#pragma mark - Private
- (void)customizeNavigationBar {
// --------------------------------------------
// 實(shí)例化一個(gè)工具條按鈕對(duì)象共啃,它將作為我們新的導(dǎo)航按鈕
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(leftButtonDidClicked:)];
// 將導(dǎo)航欄左側(cè)按鈕占调,設(shè)置為新的工具條按鈕對(duì)象
self.navigationItem.leftBarButtonItem = leftButton;
// --------------------------------------------
// 同樣為導(dǎo)航欄右側(cè)的導(dǎo)航按鈕,設(shè)置新的樣式
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemPlay
target:self
action:@selector(rightButtonDidClicked:)];
self.navigationItem.rightBarButtonItem = rightButton;
// --------------------------------------------
// 創(chuàng)建一個(gè)視圖對(duì)象移剪,它將作為我們導(dǎo)航欄的標(biāo)題區(qū)
UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
[titleView setBackgroundColor:[UIColor brownColor]];
// 新建一個(gè)標(biāo)簽對(duì)象究珊,它將顯示標(biāo)題區(qū)的標(biāo)題文字
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
label.text = @"我是自定義標(biāo)題";
[titleView addSubview:label];
// 將視圖對(duì)象設(shè)置為導(dǎo)航欄的標(biāo)題區(qū)
self.navigationItem.titleView = titleView;
}
#pragma mark - IBActions
- (void)leftButtonDidClicked:(id)sender {
NSLog(@"Left Bar Button Did Clicked!");
}
- (void)rightButtonDidClicked:(id)sender {
NSLog(@"Right Bar Button Did Clicked!");
}
10. 調(diào)整左上角返回按鈕的邊框距離
/// 直接設(shè)置
@property(nullable, nonatomic, strong) UIBarButtonItem *leftBarButtonItem;
大部分情況下,我們需要指定左邊返回按鈕距離左邊框的距離纵苛,可以如下設(shè)定:
// 【方法一】把系統(tǒng)返回按鈕替換成了 UIButton
UIButton *backBt = [UIButton buttonWithType:UIButtonTypeSystem];
backBt.frame = CGRectMake(0, 0, 20, 20);
[backBt setBackgroundImage:[UIImage imageNamed:@"back"]
forState:UIControlStateNormal];
[backBt addTarget:self
action:@selector(backToRootViewController)
forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBt];
// 【方法二】在系統(tǒng)的返回按鈕左側(cè)加了一個(gè)帶寬度的 Item
UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
initWithImage:[UIImage imageNamed:@"back"]
style:UIBarButtonItemStylePlain
target:self
action:@selector(backToRootViewController)];
UIBarButtonItem *fixedItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
target:nil
action:nil];
// 設(shè)置邊框距離剿涮,可以根據(jù)需要調(diào)節(jié)
fixedItem.width = -16;
self.navigationItem.leftBarButtonItems = @[fixedItem, leftItem];
11. 隱藏/去掉導(dǎo)航欄返回按鈕文字,只顯示一個(gè)左箭頭
// 方法一:全局設(shè)置
// 隱藏返回按鈕文字攻人,將返回按鈕的標(biāo)題垂直方向向上偏移 60 pt
// 設(shè)置/獲取標(biāo)題欄豎直位置偏移取试,UIBarMetricsDefault(豎屏)
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
// 隱藏返回按鈕文字,將返回按鈕的標(biāo)題水平方向向左偏移 100 pt
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-100, 0) forBarMetrics:UIBarMetricsDefault];
// 方法二:
// 注意此法需要在前一界面內(nèi)設(shè)置怀吻,而且不是全局的瞬浓,但是下一個(gè)界面標(biāo)題會(huì)居中
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]
initWithTitle:@""
style:UIBarButtonItemStylePlain
target:self
action:nil];
- 用方法一隱藏返回按鈕的文字以后,當(dāng)上一個(gè)視圖控制器的標(biāo)題很長(zhǎng)蓬坡,會(huì)導(dǎo)致頂層視圖控制器標(biāo)題不居中顯示的問(wèn)題猿棉,修復(fù)的方法如下(建議做成
UIViewController
范疇(category)類(lèi)):
// 如果有上個(gè)界面磅叛,將上個(gè)界面的 title 置為空,還是繞到方法二來(lái)了
- (void)resetBackButtonItem {
NSArray *viewControllerArray = [self.navigationController viewControllers];
long previousViewControllerIndex = [viewControllerArray indexOfObject:self] - 1;
UIViewController *previous;
if (previousViewControllerIndex >= 0) {
previous = [viewControllerArray objectAtIndex:previousViewControllerIndex];
previous.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]
initWithTitle:@""
style:UIBarButtonItemStylePlain
target:self
action:nil];
}
}
- 自定義導(dǎo)航欄返回按鈕萨赁,將其設(shè)置為一個(gè)
UIButton
對(duì)象弊琴,然后為按鈕設(shè)置背景圖片。
// 自定義導(dǎo)航欄返回按鈕
UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
negativeSpacer.width = 0;
UIButton *button = [[UIButton alloc] init];
// 圖片尺寸 22*22
[button setImage:[UIImage imageNamed:@"navigation_back_normal"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"navigation_back_hl"] forState:UIControlStateHighlighted];
button.frame = CGRectMake(0, 0, 33, 33);
if (@available(ios 11.0,*)) {
button.contentEdgeInsets = UIEdgeInsetsMake(0, -15,0, 0);
button.imageEdgeInsets = UIEdgeInsetsMake(0, -10,0, 0);
}
[button addTarget:self
action:@selector(backButtonTapClick)
forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:button];
viewController.navigationItem.leftBarButtonItems = @[backButton];
12. 把返回按鈕的文字替換為自定義文字
UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"返回"
style:UIBarButtonItemStylePlain
target:self
action:nil];
self.navigationItem.backBarButtonItem = leftItem;
以上代碼可以嵌入自定義的 UINavigationController
基類(lèi)中杖爽,即:
// --------- HQLBaseNavigationViewController.h ---------
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface HQLBaseNavigationViewController : UINavigationController
@end
NS_ASSUME_NONNULL_END
// --------- HQLBaseNavigationViewController.m ---------
#import "HQLBaseNavigationViewController.h"
@interface HQLBaseNavigationViewController ()
@end
@implementation HQLBaseNavigationViewController
// 執(zhí)行此方法時(shí)敲董,統(tǒng)一設(shè)置下一個(gè)視圖控制器的返回按鈕
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
// 第一個(gè) controller 左 button 不確定, 其他 controller 左 button 為特定樣式
if (self.viewControllers.count > 0) {
// 自定義導(dǎo)航欄返回按鈕文字,統(tǒng)一設(shè)置為“返回”掂林,默認(rèn)是上一個(gè)視圖控制器的標(biāo)題
UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:nil];
viewController.navigationItem.backBarButtonItem = backBarButtonItem;
// 推入下一個(gè)視圖控制器時(shí)臣缀,隱藏 TabBar 標(biāo)簽欄
viewController.hidesBottomBarWhenPushed = YES;
} else {
viewController.hidesBottomBarWhenPushed = NO;
}
[super pushViewController:viewController animated:animated];
}
@end
13. 在導(dǎo)航欄上添加多個(gè)按鈕
// 設(shè)置導(dǎo)航欄返回按鈕
UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc]
initWithTitle:@"返回"
style:UIBarButtonItemStylePlain
target:self
action:nil];
self.navigationItem.backBarButtonItem = backBarButtonItem;
// 設(shè)置導(dǎo)航欄其他按鈕
UIBarButtonItem *closeBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"關(guān)閉" style:UIBarButtonItemStylePlain target:self action:@selector(backToRootViewController)];
self.navigationItem.leftBarButtonItem = closeBarButtonItem;
// 設(shè)置左側(cè)自定義按鈕是否與返回按鈕共同存在
self.navigationItem.leftItemsSupplementBackButton = YES;
14. UINavigationControllerDelegate
// 一般用于傳遞參數(shù),或者做一些其它處理
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated;
15. 歡迎頁(yè)面時(shí)隱藏狀態(tài)欄
在項(xiàng)目的 Info.plist
文件中添加 Status bar is initially hidden
字段并設(shè)置為 YES
泻帮,可以隱藏 App 在 LunchScreen(歡迎界面)時(shí)的狀態(tài)欄:
<key>Status bar is initially hidden<key>
<value>YES<value>
16. 修改系統(tǒng)狀態(tài)欄樣式
系統(tǒng)狀態(tài)欄樣式 UIStatusBarStyle
是一個(gè)枚舉類(lèi)型:
typedef NS_ENUM(NSInteger, UIStatusBarStyle) {
// 默認(rèn)樣式精置,自動(dòng)為系統(tǒng)狀態(tài)欄設(shè)置白色或者黑色字體
UIStatusBarStyleDefault = 0,
// 白色狀態(tài)欄文本,適用于暗色背景
UIStatusBarStyleLightContent API_AVAILABLE(ios(7.0)) = 1,
// 黑色狀態(tài)欄文本锣杂,適用于亮色背景
UIStatusBarStyleDarkContent API_AVAILABLE(ios(13.0)) = 3,
// 以下兩個(gè)枚舉類(lèi)型在 iOS 7.0 之后已失效脂倦,可以不用管
UIStatusBarStyleBlackTranslucent NS_ENUM_DEPRECATED_IOS(2_0, 7_0, "Use UIStatusBarStyleLightContent") = 1,
UIStatusBarStyleBlackOpaque NS_ENUM_DEPRECATED_IOS(2_0, 7_0, "Use UIStatusBarStyleLightContent") = 2,
} API_UNAVAILABLE(tvos);
1. 全局狀態(tài)欄樣式設(shè)置:
在 AppDelegate 文件中 添加如下設(shè)置:
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
2. preferredStatusBarStyle
方法
為當(dāng)前視圖控制器添加 preferredStatusBarStyle
方法,并返回所需要的狀態(tài)欄枚舉類(lèi)型:
// 設(shè)置當(dāng)前視圖控制器系統(tǒng)狀態(tài)欄樣式
- (UIStatusBarStyle)preferredStatusBarStyle {
return UIStatusBarStyleLightContent;
}
需要注意的是:
如果該視圖控制器沒(méi)有被
UINavigationController
所擁有元莫,那么你可以直接在這個(gè)方法中設(shè)置當(dāng)前視圖控制器的系統(tǒng)狀態(tài)欄樣式赖阻。如果該視圖控制器是導(dǎo)航視圖控制器的
viewControllers
之一,則此設(shè)置無(wú)效踱蠢!
UINavigationController
不會(huì)將preferredStatusBarStyle
方法調(diào)用傳遞給它的子視圖火欧,而是由它自己管理狀態(tài),而且它也應(yīng)該那樣做茎截。因?yàn)?UINavigationController
包含了它自己的狀態(tài)欄苇侵;因此,即使被
UINavigationController
所管理的視圖控制器實(shí)現(xiàn)了preferredStatusBarStyle
方法企锌,也不會(huì)調(diào)用榆浓。
解決方法,自定義一個(gè) UINavigationController
的子類(lèi)對(duì)象撕攒,在這個(gè)子類(lèi)中重寫(xiě) preferredStatusBarStyle
方法陡鹃,讓其返回視圖控制器中的狀態(tài)欄設(shè)置。這樣在 UIViewController
中添加的 preferredStatusBarStyle
方法即可奏效抖坪,如下:
@implementation MyNavigationController
- (UIStatusBarStyle)preferredStatusBarStyle {
UIViewController *topViewController = self.topViewController;
return [topViewController preferredStatusBarStyle];
}
@end
3. 設(shè)置導(dǎo)航視圖控制器的 barStyle
屬性
// UIBarStyleBlack 為黑色導(dǎo)航欄萍鲸,此時(shí)系統(tǒng)狀態(tài)欄字體為白色!
self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
// 默認(rèn)樣式擦俐,狀態(tài)欄字體為黑色
self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
示例
在項(xiàng)目的 Targets — General — Deployment Info — Status Bar Style 全局狀態(tài)欄樣式設(shè)置為 Default:
在項(xiàng)目的 Info.plist
文件中添加如下字段猿推,將 View controller-based status bar appearance
字段的值設(shè)置為 YES
:
<key>View controller-based status bar appearance<key>
<value>YES<value>
在指定視圖控制器頁(yè)面設(shè)置系統(tǒng)狀態(tài)欄樣式:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// 進(jìn)入當(dāng)前頁(yè)面時(shí),設(shè)置指定的狀態(tài)欄樣式
self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
// 退出當(dāng)前頁(yè)面時(shí),恢復(fù)原設(shè)置
self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
}
17. 在導(dǎo)航欄添加搜索框
方式一:添加 UISearchBar
// 「搜索」按鈕
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 32)];
containerView.backgroundColor = [UIColor clearColor];
containerView.layer.cornerRadius = 16;
containerView.layer.masksToBounds = YES;
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:containerView.bounds];
// 設(shè)置搜索框中光標(biāo)的顏色
searchBar.tintColor = [UIColor lightGrayColor];
// 搜索框背景色
searchBar.backgroundColor = [UIColor whiteColor];
searchBar.placeholder = @"搜索";
searchBar.delegate = self;
[containerView addSubview:searchBar];
containerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
self.navigationItem.titleView = containerView;
// 適配 iOS 11蹬叭,通過(guò)添加高度約束 44 來(lái)固定 iOS 11 中 UISearchBar 的高度
if (@available(iOS 11.0, *)) {
[searchBar.heightAnchor constraintEqualToConstant:44].active = YES;
}
方式二:添加自定義的 UIButton
// 自定義搜索按鈕
UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
searchButton.frame = CGRectMake(0, 0, 190, 32);
searchButton.layer.cornerRadius = 16;
searchButton.layer.masksToBounds = YES;
searchButton.backgroundColor = [UIColor whiteColor];
// 標(biāo)題
[searchButton setTitle:@"搜索" forState:UIControlStateNormal];
searchButton.titleLabel.font = [UIFont systemFontOfSize:15];
[searchButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
// ?? 圖片藕咏,18*18
[searchButton setImage:[UIImage imageNamed:@"nav_sousuo"] forState:UIControlStateNormal];
searchButton.adjustsImageWhenHighlighted = NO;
// 設(shè)置圖片、標(biāo)題左對(duì)齊
searchButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
// 圖片向右移動(dòng) 10pt
searchButton.imageEdgeInsets = UIEdgeInsetsMake(0, 10.0f, 0, 0);
// 標(biāo)題向右移動(dòng) 20pt
searchButton.titleEdgeInsets = UIEdgeInsetsMake(0, 15.0f, 0, 0);
[searchButton addTarget:self action:@selector(navigationSearchButtonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.titleView = searchButton;