Hi,SwiftGG 翻译组启用了新的域名:swiftgg.team今后翻译组的各项活动将会在新域名下开展,不要错过哦!

作者:Arthur Knopper,原文链接,原文日期:2016/12/29
译者:Crystal Sun;校对:walkingway;定稿:CMB

状态栏可以有两种外观:dark(黑色) 和 light(白色)。在本章教程中,将学习如何改变状态栏的外观。本节教程使用的是 Xcode 8.0 和 iOS 10。

打开 Xcode,创建一个 Single View Application。

Product Name 使用 IOS10StatusBarColorTutorial,填写自己的 Organization Name 和 Organization Identifier,Language 一栏选择 Swift,Devices 一栏选择 iPhone。

打开 Storyboard,选中 View,在 Attributes Inspetor 里将 Background Color 改成 Light Gray。运行工程,默认的状态栏颜色是黑色(dark)。

而我们想要实现的效果是白色的状态栏。打开 ViewController.swift 文件,添加下列代码:

override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}

上述代码将 UIStatusBarStyle 枚举项设为 lightContent。运行工程,这时状态栏的颜色变成了白色(light)。

接下来回到 Storyboard,选中 View Controller,在 Editor 菜单中选择 Embed in Navigation Controller。选中 Navigation Bar,在 Attribute Inspector 里将 Bar Tint color 设置为 red。storyboard 应该如下图所示。

运行工程,状态栏又变成了黑色,也就是默认状态。产生这个问题的原因是,iOS 请求的是 navigation controller 状态栏风格,不是 navigation controller 所包含的 controller 风格。

为了改变 Navigation controller 的风格(style),需要在 AppDelegate.swift 文件里如下修改代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.

UINavigationBar.appearance().barStyle = .blackOpaque
return true
}

运行工程,这时状态栏的颜色变成了白色。

可以从 github 上下载 IOS10StatusBarColorTutorial 教程的源代码。

本文由 SwiftGG 翻译组翻译,已经获得作者翻译授权,最新文章请访问 http://swift.gg

文章目录