我想移除屏幕顶部的状态栏。

这行不通:

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

我也试过:

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
}

当前回答

更新为iOS 13和Swift 5

如果以上答案都不适合你。检查你的plist,看看你是否有这个:

“基于视图控制器的状态栏外观”

如果是,请确保将其设置为YES!!!!!

然后下面的代码将工作。

override var prefersStatusBarHidden: Bool {
    return true
}

其他回答

你可以在你的ViewController类范围内使用这段代码

open override var prefersStatusBarHidden: Bool { return true }

斯威夫特 5+

在我的例子中,我需要根据某些条件更新隐藏的状态栏。

因此,我创建了一个包含新属性hideStatusBar的基本控制器BaseViewController。

其他视图控制器是这个基控制器的子类。最后,当我想要更新状态栏行为时,我只需要更改这个hideStatusBar值。

class BaseViewController: UIViewController {

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

    override var prefersStatusBarHidden: Bool {
           return hideStatusBar
    }
}

如何使用

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

这是一个演示,我使用UIView.animate(…)使过渡更流畅。

斯威夫特3

在信息。plist设置基于控制器的状态栏外观为NO

调用uiapplication。shared。isstatusbarhidden = true

在Swift 3.x:

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

在我的情况下,我正在寻找状态栏隐藏/显示的需求;而不是只在视图加载或消失的时候。

快3.倍

//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()