如何在 iOS 11 上的 iPhone X 上获得黑色状态栏

How to get a black statusbar on iPhone X on iOS 11

默认情况下,iPhone X 上的状态栏如下所示:

但我想实现这个:

我尝试将 preferredStatusBarStyle 设置为 lightContent 但只有在将状态栏后面的背景设置为黑色后它才起作用。

为了修复圆角,我最终添加了另一个带圆角的子视图。

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .black

        let roundedView = UIView(
            frame: CGRect(
                x: 0,
                y: UIApplication.shared.statusBarFrame.height,
                width: view.frame.width,
                height: view.frame.height
            )
        )
        roundedView.layer.cornerRadius = 10
        roundedView.layer.masksToBounds = true
        roundedView.backgroundColor = .white
        view.addSubview(roundedView)

        let label = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 60))
        label.text = "Black statusbar!"
        label.textAlignment = .center
        roundedView.addSubview(label)
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}

我想知道这是否是最好的方法.. 必须有更好的方法来实现这一点。


更新

这是个糟糕的主意,因为:

Don't mask or call special attention to key display features. Don't attempt to hide the device's rounded corners, sensor housing, or indicator for accessing the Home screen by placing black bars at the top and bottom of the screen. Don't use visual adornments like brackets, bezels, shapes, or instructional text to call special attention to these areas either.

安全区域布局可以解决您的问题。

我尝试在我现有的项目中遵循该解决方案,它工作正常。

  • 将黑色背景颜色(或任何你想要的)设置为视图控制器的主视图。
  • 现在添加子视图(白色背景)并设置其相对于安全区域布局的约束(如果 Xcode 版本低于 9,则遵循顶部和底部布局指南)。
  • 将此子视图(白色背景)视为主视图,并使用它进行进一步设计。

这是带有结果的示例快照,通过启用或禁用安全区域布局,我进行了测试和实施。

仅供参考:在这些快照中,主视图的背景为红色,子视图的背景为蓝色。

安全区布局:

AutoLayout