![](/img/trans.png)
[英]Swift: Changing view/screen depending on device orientation. What is “efficiency wise” the better option?
[英]Swift changing constraints depending on device orientation
當設備從縱向旋轉到橫向時,視圖的寬度約束會更新,但在設備從橫向旋轉到縱向時不會更新
我的代碼:
override func viewDidLoad() {
super.viewDidLoad()
theView.translatesAutoresizingMaskIntoConstraints = false
theView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
theView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
theView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
theView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
當設備首次從縱向旋轉到橫向時,“視圖”寬度獲得視圖寬度的50%
if UIDevice.current.orientation.isLandscape {
theView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.50).isActive = true
從橫向旋轉到縱向不會恢復原始寬度
} else {
theView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.00).isActive = true
}
}
這是一張圖片,顯示了我想要做的事情。
您應該在旋轉時禁用右錨點約束。
由於NSLayoutAnchor
類的constraint
方法始終返回新的非活動約束,因此應保留對要激活/取消激活的約束的引用。
初始化可能如下所示。
override func viewDidLoad() {
super.viewDidLoad()
// ...
widthConstraint = theView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.50)
rightConstraint = theView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0)
rightConstraint.isActive = true
}
有了這些參考,你就可以像這樣實現你的willRotate:
方法。
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isLandscape {
rightConstraint.isActive = false
widthConstraint.isActive = true
}
else {
rightConstraint.isActive = true
widthConstraint.isActive = false
}
}
它看起來應該是這樣的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.