根据设备方向快速更改约束

时间:2017-11-02 18:54:15

标签: ios swift constraints

当设备从纵向旋转到横向时,视图的宽度约束会更新,但是当设备从横向旋转到纵向时它不会更新

我的代码:

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) {

当设备首次从纵向旋转到横向时,视图' width获得视图宽度的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
    }   
}

这是一张显示我想要做的事情的图片。

enter image description here

1 个答案:

答案 0 :(得分:4)

旋转时应禁用右锚点约束。

由于constraint类的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
}

有了这些参考资料,您可以像这样实施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
    }
}

应该是这样的。

Ilustration of the solution