我把safeAreaLayoutGuide设成这样:
let guide = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
topControls.topAnchor.constraint(equalTo: guide.topAnchor, constant: 0)
])这个很好用。然而,当我旋转设备到景观模式,没有状态栏(电池,信号等),从屏幕顶部的偏移是零。这是正确的,基于锚。然而,这看起来不太好。如何在创建锚期间为景观添加偏移量20?我不想根据方向手动改变常量。
发布于 2018-01-01 12:28:34
假设您在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)方法和交换基于新的定向/大小类的两个约束的活动状态。
需要注意的一件事是,总是先禁用约束,然后激活约束,以避免抱怨无法满足的约束。
https://stackoverflow.com/questions/48049297
复制相似问题