假设您在 iPhone 上运行,那么这是预期的行为,可以通过覆盖以下内容进行更改:
override var prefersStatusBarHidden: Bool {
return false
}
根据该 UIViewController 方法的描述:
默认情况下,此方法返回 false,但有一个例外。对于链接到 iOS 8 或更高版本的应用程序,如果视图控制器处于垂直紧凑环境中,则此方法返回 true。
如果您覆盖它,那么您将获得一个横向的状态栏,并且安全区域指南将相应地进行调整。
编辑
所以对原来的要求有一点误解。这不是显示状态栏,而是有一个间隙,就像有一个状态栏一样。
这需要手动完成,因为您无法手动设置仅适用于某些方向/尺寸类别的约束。
这是一个基本的 UIViewController 将做你正在寻找的东西:
class ViewController: UIViewController {
var testView: UIView!
var landscapeConstraint: NSLayoutConstraint!
var portraitConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.testView = UIView()
self.testView.backgroundColor = .green
self.view.addSubview(self.testView)
self.testView.translatesAutoresizingMaskIntoConstraints = false
let guide = view.safeAreaLayoutGuide
self.testView.leftAnchor.constraint(equalTo: guide.leftAnchor, constant: 0).isActive = true
self.testView.rightAnchor.constraint(equalTo: guide.rightAnchor, constant: 0).isActive = true
self.testView.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: 0).isActive = true
self.portraitConstraint = self.testView.topAnchor.constraint(equalTo: guide.topAnchor, constant: 0)
self.landscapeConstraint = self.testView.topAnchor.constraint(equalTo: guide.topAnchor, constant: 20) // Hardcoded the size but this can be anything you want.
switch self.traitCollection.verticalSizeClass {
case .compact:
self.landscapeConstraint.isActive = true
case.regular:
self.portraitConstraint.isActive = true
default: // This shouldn't happen but let's assume regular (i.e. portrait)
self.portraitConstraint.isActive = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
switch newCollection.verticalSizeClass {
case .compact:
self.portraitConstraint.isActive = false
self.landscapeConstraint.isActive = true
case.regular:
self.landscapeConstraint.isActive = false
self.portraitConstraint.isActive = true
default: // This shouldn't happen but let's assume regular (i.e. portrait)
self.landscapeConstraint.isActive = false
self.portraitConstraint.isActive = true
}
}
}
基本上你设置了固定约束,即左、右和下,然后设置纵向和横向的约束(常规和紧凑的垂直尺寸类),默认情况下它们都是禁用的。然后您根据当前的方向/尺寸类决定激活哪一个。然后你覆盖:
willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator)
基于新的方向/大小类的方法和交换两个约束的活动状态。
需要注意的一件事是始终先停用约束,然后再激活约束,以避免任何抱怨无法满足的约束。