Nic*_*oli 3 constraints ios swift
当设备从纵向旋转到横向时,视图的宽度约束会更新,但是当设备从横向旋转到纵向时,视图的宽度约束不会更新
我的代码:
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) {
Run Code Online (Sandbox Code Playgroud)
首次将设备从纵向旋转为横向时,“ theView”宽度为视图宽度的50%
if UIDevice.current.orientation.isLandscape {
theView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.50).isActive = true
Run Code Online (Sandbox Code Playgroud)
从横向旋转到纵向无法恢复原始宽度
} else {
theView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.00).isActive = true
}
}
Run Code Online (Sandbox Code Playgroud)
这是一张图像,显示了我正在尝试做的事情。
旋转时,应禁用右锚约束。
因为类的constraintmethod NSLayoutAnchor总是返回新的非活动约束,所以您应保留对要激活/停用的约束的引用。
初始化可能看起来像这样。
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
}
Run Code Online (Sandbox Code Playgroud)
有了这些引用,您可以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
}
}
Run Code Online (Sandbox Code Playgroud)
它应该看起来像这样。
| 归档时间: |
|
| 查看次数: |
2086 次 |
| 最近记录: |