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

标签 ios swift constraints

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

我的代码:

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

当设备第一次从纵向旋转到横向时,“theView”宽度获得 View 宽度的 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

最佳答案

旋转时应该禁用右 anchor 约束。

因为 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
    }
}

它应该是这样的。

Ilustration of the solution

关于ios - 根据设备方向快速更改约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47082655/

相关文章:

iphone - 将样本音频44100Kz下调至8000Kz

swift - self.tabBarController.selectedIndex 不调用 viewDidAppear

php - 如果我总是使用 PHP 控制我的数据库输入,像 NOT NULL 和 FOREIGN KEY 这样的约束有多重要?

ios - Xcode 约束未按预期工作

swift - 添加活力时,保留按钮上的界面构建器约束

ios - 一个 Bundle ID 的多个推送证书

ios - UITableViewCells 显示在表格 View 容器之外

IOS 自定义 Segue 和 ContainerView

swift - Swift 上的文本字段第一响应者到下一个响应者

xcode - 如何在联系人体内使用 node.name?