ios 在 Swift 3 中更改状态栏背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39802420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 10:25:17  来源:igfitidea点击:

Change Status Bar Background Color in Swift 3

iosswiftswift3statusbaruistatusbar

提问by derdida

In XCode 7.3.x ill changed the background Color for my StatusBar with:

在 XCode 7.3.x 中,我用以下方法更改了我的 StatusBar 的背景颜色:

func setStatusBarBackgroundColor(color: UIColor) {
guard  let statusBar = UIApplication.sharedApplication().valueForKey("statusBarWindow")?.valueForKey("statusBar") as? UIView else {
    return
}
statusBar.backgroundColor = color
}

But it seems that this is not working anymore with Swift 3.0.

但似乎这不再适用于 Swift 3.0。

Ill tried with:

我试过:

func setStatusBarBackgroundColor(color: UIColor) {
guard  let statusBar = (UIApplication.shared.value(forKey: "statusBarWindow") as AnyObject).value(forKey: "statusBar") as? UIView else {
    return
}
statusBar.backgroundColor = color
}

But it gives me:

但它给了我:

this class is not key value coding-compliant for the key statusBar.

Any Ideas how to change it with XCode8/Swift 3.0?

任何想法如何使用 XCode8/Swift 3.0 更改它?

回答by Callam

extension UIApplication {
    var statusBarView: UIView? {
        if responds(to: Selector(("statusBar"))) {
            return value(forKey: "statusBar") as? UIView
        }
        return nil
    }
}

UIApplication.shared.statusBarView?.backgroundColor = .red

Update for iOS 13

iOS 13 更新

App called -statusBar or -statusBarWindow on UIApplication: this code must be changed as there's no longer a status bar or status bar window. Use the statusBarManager object on the window scene instead.

在 UIApplication 上调用 -statusBar 或 -statusBarWindow 的应用程序:必须更改此代码,因为不再有状态栏或状态栏窗口。改为在窗口场景中使用 statusBarManager 对象。

Refer to How to change the status bar background color and text color on iOS 13?

请参阅如何在 iOS 13 上更改状态栏背景颜色和文本颜色?

回答by Daniel Illescas

"Change" status bar background color:

“更改”状态栏背景颜色:

let statusBarView = UIView(frame: UIApplication.shared.statusBarFrame)
let statusBarColor = UIColor(red: 32/255, green: 149/255, blue: 215/255, alpha: 1.0)
statusBarView.backgroundColor = statusBarColor
view.addSubview(statusBarView)

Change status bar text color:

更改状态栏文本颜色:

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

Update:please note that the status bar frame will change when the view is rotated. You could update the created subview frame by:

更新:请注意,当视图旋转时,状态栏框架会发生变化。您可以通过以下方式更新创建的子视图框架:

  • Using the autoresizing mask: statusBarView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
  • Observing NSNotification.Name.UIApplicationWillChangeStatusBarOrientation
  • Or overriding viewWillLayoutSubviews()
  • 使用自动调整大小掩码: statusBarView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
  • 观察 NSNotification.Name.UIApplicationWillChangeStatusBarOrientation
  • 或覆盖 viewWillLayoutSubviews()

回答by abdullahselek

With using Swift 3 and 4you can use the code snippet on below. It finds the view from UIApplicationusing valueForKeyPathas set it's background color.

使用Swift 3 和 4,您可以使用下面的代码片段。它从UIApplication使用valueForKeyPath设置的背景颜色中找到视图。

guard let statusBarView = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView else {
        return
    }
statusBarView.backgroundColor = UIColor.red

Objective-C

目标-C

UIView *statusBarView = [UIApplication.sharedApplication valueForKeyPath:@"statusBarWindow.statusBar"];
if (statusBarView != nil)
{
    statusBarView.backgroundColor = [UIColor redColor];
}

回答by Jamil Hasnine Tamim

For Xcode 9 and iOS 11:The style of the status bar we will try to achieve is a status bar with white content. Go to the ViewController.swift file and add the following lines of code.

对于 Xcode 9 和 iOS 11:我们将尝试实现的状态栏样式是带有白色内容的状态栏。转到 ViewController.swift 文件并添加以下代码行。

override var preferredStatusBarStyle: UIStatusBarStyle {

     return .lightContent

}

Or from project settings option you can change status bar's style:

或者从项目设置选项中,您可以更改状态栏的样式:

enter image description here

在此处输入图片说明

Next, go back to the Storyboard, Select the View Controller and in the Editor menu Select Embed in Navigation Controller. Select the Navigation Bar and in the Attribute Inspector set the Bar Tint color to red. The Storyboard will look like this. enter image description here

接下来,返回 Storyboard,选择 View Controller 并在 Editor 菜单中选择 Embed in Navigation Controller。选择 Navigation Bar,然后在 Attribute Inspector 中将 Bar Tint 颜色设置为红色。故事板将如下所示。 在此处输入图片说明

Build and Run the project, The content of the status bar is dark again, which is the default. The reason for this is, iOS asked for the style of the status bar of the navigation controller instead of the contained view controller.

Build and Run工程,状态栏的内容又变黑了,这是默认的。这样做的原因是,iOS 要求导航控制器的状态栏样式而不是包含的视图控制器。

enter image description here

在此处输入图片说明

To change the style of all navigation controller inside the app, change the following method in the AppDelegate.swift file.

要更改应用程序内所有导航控制器的样式,请更改 AppDelegate.swift 文件中的以下方法。

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

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

Build and Run the Project again, this time the content of the status bar changed to white.

再次构建并运行项目,这次状态栏的内容变成了白色。

enter image description here

在此处输入图片说明

回答by Asfand Shabbir

For iOS 11 and Xcode 9use the following steps.

对于iOS 11 和 Xcode 9,请使用以下步骤。

  1. create an extention to UIApplicationclass:

    extension UIApplication { var statusBarView: UIView? { return value(forKey: "statusBar") as? UIView } }

  2. In your class or wherever you want to change the Status bar's background color:

    UIApplication.shared.statusBarView?.backgroundColor = .red

  3. For light content or dark content of status bar simply go to Info.plistand add the following value row with value NO.

  1. 创建UIApplication类的扩展:

    extension UIApplication { var statusBarView: UIView? { return value(forKey: "statusBar") as? UIView } }

  2. 在您的课堂上或您想要更改状态栏背景颜色的任何地方:

    UIApplication.shared.statusBarView?.backgroundColor = .red

  3. 对于状态栏的亮内容或暗内容,只需转到Info.plist并添加以下值为NO 的值行。

View controller-based status bar appearance

查看基于控制器的状态栏外观

  1. Now just set the light content or whatever you need in the General Tab of your project's settings.
  1. 现在只需在项目设置常规选项卡中设置灯光内容或您需要的任何内容。

回答by ioSana

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

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

This works for me, as my navigation barTintColor was black and unable to see the status bar.

这对我有用,因为我的导航 barTintColor 是黑色的,无法看到状态栏。

When set above code it didFinishLaunch status bar appears in white.

当设置上面的代码时,它 didFinishLaunch 状态栏显示为白色。

回答by Vipin Saini

Try this

尝试这个

Goto your app info.plist

转到您的应用程序 info.plist

  1. Set View controller-based status bar appearance to NO
  2. Set Status bar style to UIStatusBarStyleLightContent
  1. 将基于视图控制器的状态栏外观设置为 NO
  2. 将状态栏样式设置为 UIStatusBarStyleLightContent

Then Goto your app delegate and paste the following code where you set your Windows's RootViewController.

然后转到您的应用程序委托并将以下代码粘贴到您设置 Windows 的 RootViewController 的位置。

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 20)];
    view.backgroundColor=[UIColor blackColor];
    [self.window.rootViewController.view addSubview:view];
}

回答by FreakyCoder

I have a custom solution for changing status bar on iOS 13 and below. Here is how to do that:

我有一个自定义解决方案,用于在 iOS 13 及更低版本上更改状态栏。以下是如何做到这一点:

if #available(iOS 13.0, *) {
   let app = UIApplication.shared
   let statusBarHeight: CGFloat = app.statusBarFrame.size.height

   let statusbarView = UIView()
   statusbarView.backgroundColor = UIColor.red
   view.addSubview(statusbarView)

   statusbarView.translatesAutoresizingMaskIntoConstraints = false
   statusbarView.heightAnchor
     .constraint(equalToConstant: statusBarHeight).isActive = true
   statusbarView.widthAnchor
     .constraint(equalTo: view.widthAnchor, multiplier: 1.0).isActive = true
   statusbarView.topAnchor
     .constraint(equalTo: view.topAnchor).isActive = true
   statusbarView.centerXAnchor
     .constraint(equalTo: view.centerXAnchor).isActive = true

} else {
      let statusBar = UIApplication.shared.value(forKeyPath: 
   "statusBarWindow.statusBar") as? UIView
      statusBar?.backgroundColor = UIColor.red
}

Gist

要旨

Also, check the article iOS 13 How to Change StatusBar Color?

另外,请查看文章iOS 13 如何更改状态栏颜色?

One last thing, you can still change statusbar style with :

最后一件事,您仍然可以使用以下命令更改状态栏样式:

 override var preferredStatusBarStyle : UIStatusBarStyle {
    return UIStatusBarStyle.lightContent
    //return UIStatusBarStyle.default   // Make dark again
}

回答by Rifat Monzur

I made this extension to change color of status bar. It's not dependent on the key. So it is much safer to use

我做了这个扩展来改变状态栏的颜色。它不依赖于密钥。所以使用起来更安全

public extension UIViewController {
    func setStatusBar(color: UIColor) {
        let tag = 12321
        if let taggedView = self.view.viewWithTag(tag){
            taggedView.removeFromSuperview()
        }
        let overView = UIView()
        overView.frame = UIApplication.shared.statusBarFrame
        overView.backgroundColor = color
        overView.tag = tag
        self.view.addSubview(overView)
    }
}

Here is usage anywhere in viewcontroller:

这是视图控制器中任何地方的用法:

setStatusBar(color: .red)

setStatusBar(color: .red)

回答by Krunal

You can set background color for status bar during application launch or during viewDidLoad of your view controller.

您可以在应用程序启动期间或视图控制器的 viewDidLoad 期间设置状态栏的背景颜色。

extension UIApplication {

    var statusBarView: UIView? {
        return value(forKey: "statusBar") as? UIView
    }

}

// Set upon application launch, if you've application based status bar
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        UIApplication.shared.statusBarView?.backgroundColor = UIColor.red
        return true
    }
}


or 
// Set it from your view controller if you've view controller based statusbar
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        UIApplication.shared.statusBarView?.backgroundColor = UIColor.red
    }

}



Here is result:



这是结果:

enter image description here

在此处输入图片说明