简体   繁体   English

如何在 Swift iOS 应用中隐藏状态栏?

[英]How do I hide the status bar in a Swift iOS app?

I'd like to remove the status bar at the top of the screen.我想删除屏幕顶部的状态栏。

This does not work:这不起作用:

func application
(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: NSDictionary?)
-> Bool
{
        application.statusBarHidden = true
        return true
}

I've also tried:我也试过:

func application
(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: NSDictionary?)
-> Bool
{
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

    var controller = UIViewController()
    application.statusBarHidden = true
    controller.setNeedsStatusBarAppearanceUpdate()

    var view = UIView(frame: CGRectMake(0, 0, 320, 568))
    view.backgroundColor = UIColor.redColor()
    controller.view = view

    var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
    label.center = CGPointMake(160, 284)
    label.textAlignment = NSTextAlignment.Center
    label.text = "Hello World"
    controller.view.addSubview(label)

    self.window!.rootViewController = controller
    self.window!.makeKeyAndVisible()
    return true
}

You really should implement prefersStatusBarHidden on your view controller(s):你真的应该在你的视图控制器上实现 prefersStatusBarHidden:

Swift 3 and later Swift 3 及更高版本

override var prefersStatusBarHidden: Bool {
    return true
}
  1. Go to Info.plist file转到 Info.plist 文件
  2. Hover on one of those lines and a (+) and (-) button will show up.将鼠标悬停在其中一行上,将显示 (+) 和 (-) 按钮。
  3. Click the plus button to add new key Type in start with capital V and automatically the first choice will be View controller-based status bar appearance.单击加号按钮以添加新的键键入以大写 V 开头,第一个选项将自动成为基于视图控制器的状态栏外观。
  4. Add that as the KEY.将其添加为 KEY。
  5. Set the VALUE to "NO"将值设置为“否”
  6. Go to you AppDelegate.swift去找你 AppDelegate.swift
  7. Add the code, inside the method在方法内添加代码

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject:AnyObject]?) -> Bool { application.statusBarHidden = true return true }

DONE!完毕! Run your app and no more status bar!运行您的应用程序,不再有状态栏!

Swift 3斯威夫特 3

In Info.plist set View controller-based status bar appearance to NOInfo.plistView controller-based status bar appearanceNO

And call UIApplication.shared.isStatusBarHidden = true并调用UIApplication.shared.isStatusBarHidden = true

If you want to hide and bring back the status bar on button tap , while at the time of presenting and dismissing slide-in menu , popups etc, then you can use this method:-如果您想在按钮点击时隐藏和恢复状态栏,而在呈现和关闭滑入菜单弹出窗口等时,则可以使用此方法:-

To hide the status bar:-隐藏状态栏:-

UIApplication.shared.keyWindow?.windowLevel = UIWindowLevelStatusBar

To bring back the status bar:-要恢复状态栏:-

UIApplication.shared.keyWindow?.windowLevel = UIWindowLevelNormal 

if you prefer a visual approach rather than coding it use this method: in your info.plist如果您更喜欢视觉方法而不是编码,请使用此方法:在您的info.plist

在此处输入图片说明 simply add View controller-based status bar appearance to NO只需将View controller-based status bar appearanceNO

and Status bar is initially hidden as YES并且Status bar is initially hiddenYES

Update for iOS 10 / Swift 3.0 iOS 10 / Swift 3.0 更新

No longer a function, now a property...不再是一个函数,现在是一个属性......

override var prefersStatusBarHidden: Bool {
    return true
}
 override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true);
    navigationController?.navigationBar.hidden = true // for navigation bar hide
    UIApplication.sharedApplication().statusBarHidden=true; // for status bar hide
}

Go to your Info.plist and add two Keys:转到您的 Info.plist 并添加两个键:

转到您的 Info.plist 并添加两个键:

in Swift 3.x:在 Swift 3.x 中:

override func viewWillAppear(_ animated: Bool) {
    UIApplication.shared.isStatusBarHidden = true
}

So the issue here actually has nothing to do with Swift but just how status bar appearance is handled as of iOS 7.所以这里的问题实际上与 Swift 无关,而是从 iOS 7 开始如何处理状态栏外观。

By Default, view controllers individually control the appearance of the status bar when they are on the screen.默认情况下,视图控制器单独控制状态栏在屏幕上的外观。 If you want to use this method of controlling the status bar, you can override the following methods for whatever view controllers you'd like to modify the appearance for:如果你想使用这种控制状态栏的方法,你可以为你想要修改外观的任何视图控制器覆盖以下方法:

prefersStatusBarHidden , preferredStatusBarStyle , preferredStatusBarAnimation , prefersStatusBarHiddenpreferredStatusBarStylepreferredStatusBarAnimation

In your case, you would just implement prefersStatusBarHidden and return true .在您的情况下,您只需实现prefersStatusBarHidden并返回true

The other way would be to control the status bar appearance at the application level.另一种方法是在应用程序级别控制状态栏外观。 This seems to be what you're actually trying to do (by setting application.statusBarHidden ).这似乎是你真正想要做的(通过设置application.statusBarHidden )。

In order to make this work, you need to open up your app's Info.plist file and add the key UIViewControllerBasedStatusBarAppearance , and give it a value of NO .为了让这个工作,你需要打开你的应用程序的Info.plist文件并添加键UIViewControllerBasedStatusBarAppearance ,并给它一个值NO

Swift 5+斯威夫特 5+

In my case, I need to update the status bar hidden based on some conditions.就我而言,我需要根据某些条件更新隐藏的状态栏。

Because of this, I create a base controlller BaseViewController which contains new property hideStatusBar .因此,我创建了一个包含新属性hideStatusBar的基本控制器BaseViewController

Other view controllers are sub-class of this base controller.其他视图控制器是这个基本控制器的子类。 Finally when I want to update the status bar behavior, I only need to change this hideStatusBar value.最后,当我想更新状态栏行为时,我只需要更改此hideStatusBar值。

class BaseViewController: UIViewController {

    var hideStatusBar: Bool = false {
        didSet {
            setNeedsStatusBarAppearanceUpdate()
        }
    }

    override var prefersStatusBarHidden: Bool {
           return hideStatusBar
    }
}

How to use如何使用

final class ViewController: BaseViewController, UIScrollViewDelegate {
    let scrollView = UIScrollView()

    ...

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        UIView.animate(withDuration: 0.3) {
            if scrollView.contentOffset.y > 100 {
                self.hideStatusBar = true
            } else {
                self.hideStatusBar = false
            }
        }
    }
}

Demo演示

Here is a demo, I'm using UIView.animate(...) to make the transition smoother.这是一个演示,我使用UIView.animate(...)使过渡更平滑。

在此处输入图片说明

I actually figured this out myself.其实我自己想通了。 I'll add my solution as another option.我将添加我的解决方案作为另一种选择。

extension UIViewController {
    func prefersStatusBarHidden() -> Bool {
        return true
    }
}

Okay, so this become a problem for me since iOS 9 doesn't support any above the method people have mentioned here such as UIApplication.sharedApplication().statusBarHidden = true or好的,所以这对我来说成了一个问题,因为 iOS 9 不支持人们在这里提到的任何上述方法,例如UIApplication.sharedApplication().statusBarHidden = true

UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: UIStatusBarAnimation.None)

and

override func prefersStatusBarHidden() -> Bool {
     return true
}

works but does not provide programable solution where I can change on a condition.有效,但不提供我可以根据条件进行更改的可编程解决方案。 ( statusBarHidden = true and statusBarHidden = false as we have done before). statusBarHidden = truestatusBarHidden = false正如我们之前所做的那样)。

Solution to this madness:解决这个疯狂的方法:

By adding to prefersStatusBarHidden() like below you can programmatically control the hide and show of status bar without adding UIViewControllerBasedStatusBarAppearance setting to your info.plist :通过像下面这样添加到prefersStatusBarHidden() ,您可以以编程方式控制状态栏的隐藏和显示,而无需将UIViewControllerBasedStatusBarAppearance设置添加到您的info.plist

var showStatusBar = true

override func prefersStatusBarHidden() -> Bool {
     if showStatusBar {
         return false
     }
     return true
}

private func showStatusBar(enabled: Bool) {
    showStatusBar = enabled
    prefersStatusBarHidden()
}

then use it like this throughout your code:然后在整个代码中像这样使用它:

//Hide Status Bar
showStatusBar(false)

OR或者

//Show Status Bar
showStatusBar(true)

补充一下,在覆盖prefersStatusBarHidden方法或变量时,Info.plist中View controller-based status bar appearance必须为YES,否则覆盖将无效

in Swift 4.2 it is a property now.在 Swift 4.2 中,它现在是一个属性。

override var prefersStatusBarHidden: Bool {
    return true
}

In my case, I was looking for the status bar to hide/show on demand;就我而言,我正在寻找状态栏以按需隐藏/显示; instead of just when the view loads or disappears.而不仅仅是在视图加载或消失时。

swift 3.x快速 3.x

//show status bar initially
var showStatusBar = true

//set the parameters
override var prefersStatusBarHidden: Bool {

    if showStatusBar == true {

        //does not prefer status bar hidden
        print("does not prefer status bar hidden")
        return false

    } else {

        //does prefer status bar hidden
        print("does prefer status bar hidden")
    return true

    }
}

//ex: hide status bar and call parameter function again whenever you want
        showStatusBar = false
        setNeedsStatusBarAppearanceUpdate()

Swift 5: In the main view controller, or main navigation controller if you have, Swift 5:在主视图控制器或主导航控制器(如果有)中,

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

    override var prefersStatusBarHidden: Bool {
        return false
    }

And "View controller-based status bar appearance" in plist must be YES, otherwise the above code will not be called.并且plist中的“View controller-based status bar appearance”必须为YES,否则上面的代码不会被调用。

If you want to hide status bar when launching app, "Status bar is initially hidden" in plist must be YES.如果您想在启动应用程序时隐藏状态栏,plist 中的“状态栏最初是隐藏的”必须为 YES。 This can prevent launch image from being distorted when extra blue bar showing on screen top.当屏幕顶部显示额外的蓝条时,这可以防止启动图像失真。

A solution that works for me;一个对我有用的解决方案; if you want to hide the status bar on a specific view controller while loading:如果要在加载时隐藏特定视图控制器上的状态栏:

import UIKit

class ViewController: UIViewController {

private var hideStatusBar: Bool = false

override var prefersStatusBarHidden: Bool {
    return hideStatusBar
}

override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
    return UIStatusBarAnimation.slide
}

override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundcolor = .white
    hideStatusBar = true

    UIView.animate(withDuration: 0.3) {
        self.setNeedsStatusBarAppearanceUpdate()
    }
}

Attention: if you set the key " View controller-based status bar appearance " to " NO " in your info.plist the code above doesn't work.注意:如果您在 info.plist 中将键“基于控制器的状态栏外观”设置为“”,则上面的代码不起作用。 You should set the key to " YES " or remove it from info.plist您应该将密钥设置为“ YES ”或其从 info.plist 中删除

在您的项目 General->Deployment Info->Status bar style 中选择 Hide status bar 的复选标记注意:- 它在整个应用程序中隐藏状态栏

For Swift 4+ try the following code (tested on Swift 4.0, 4.1 - IOS 10, 11) :对于 Swift 4+,请尝试以下代码(在 Swift 4.0、4.1 - IOS 10、11 上测试):

override var prefersStatusBarHidden: Bool { return true }

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    // call this func to force preferredStatusBarStyle to be read again.
    setNeedsStatusBarAppearanceUpdate()
}

Updated for iOS 13 and Swift 5针对 iOS 13 和 Swift 5 更新

If none of the above answers work for you.如果以上答案都不适合您。 Check your plist to see if you have this:检查你的 plist 看看你是否有这个:

"View controller-based status bar appearance" “查看基于控制器的状态栏外观”

If so, be sure to set it to YES!!!!!如果是这样,请务必将其设置为 YES!!!!

Then the following code will work.然后下面的代码将起作用。

override var prefersStatusBarHidden: Bool {
    return true
}

I'm using Xcode 8.1 (8B62) with a deployment target set to 10.1 and I haven't had much luck with the override options mentioned above.我正在使用 Xcode 8.1 (8B62) 并将部署目标设置为 10.1,但我对上述覆盖选项的运气不佳。 However checking the "Hide status bar" option in Deployment Info did the trick for me.然而,检查部署信息中的“隐藏状态栏”选项对我来说很有效。

Project > General项目 > 一般

I hope this helps.我希望这有帮助。

If you are presenting the view controller modally, try如果您以模态方式呈现视图控制器,请尝试

viewController.hidesBottomBarWhenPushed = true
viewController.modalPresentationCapturesStatusBarAppearance = true
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        application.isStatusBarHidden = true
        return true
    }

您可以在ViewController Class scope使用此代码

open override var prefersStatusBarHidden: Bool { return true }

In your Project->General->Deployment info在您的项目->常规->部署信息中

Statusbar Style:--状态栏样式:--

just marked Hide status Bar(iOS 10)刚刚标记隐藏状态栏(iOS 10)

Swift 4斯威夫特 4

//MARK:- Show Status Bar
UIApplication.shared.isStatusBarHidden = false

//MARK:- Hide Status Bar
UIApplication.shared.isStatusBarHidden = true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM