ios - 更新设备方向上的 widthAnchor

标签 ios swift constraints nslayoutconstraint nslayoutanchor

对于这样的 View ,我的 Controller 中有这样的约束:

someView.widthAnchor.constraint(equalToConstant: view.bounds.width).isActive = true

现在我已在 willLayoutSubviews 中添加了此约束,以在设备旋转时更新它。

但它似乎没有更新,甚至更像是添加了另一个宽度约束,这当然与旧的宽度约束冲突。

现在我真的不知道更新此宽度约束的正确解决方案,但在我看来,我需要先删除约束,然后再次设置它。

如果我这样测试:

someView.constraints.forEach {
    someView.removeContraint($0)
}

这按预期工作,只是它当然删除了一些我不想删除的约束......所以也不是解决方案。

最佳答案

Sol1

将宽度约束 Hook 为IBOutlet并在代码中更改其常量,如下所示

self.widthCon.constant = //value
self.view.layoutIfNeeded()

Sol2

删除带有标识符的约束

someView.constraints.forEach {
   if $0.identifier == "set_id" {
      someView.removeConstraint($0)
      someView.widthAnchor.constraint(equalToConstant: view.bounds.width).isActive = true
   }
}

关于ios - 更新设备方向上的 widthAnchor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50320589/

相关文章:

ios - 如何检测 AVPlayer 中的缓冲?

ios - 使用来自 URL 的图像显示 UIImage

json - 除非主函数快速完成,否则从函数调用函数不会返回值

ios - Xcode 7 到 8 : Size Classes

android-layout - 这个 View 没有约束,它只有设计时的位置,所以它会跳到 (0,0) 除非你添加约束

ios - 表情符号未在 Swift 中显示

ios - 重新定义目标操作方法以便 `UIButtons` 将消息中继到我的 `UIViewController` 中的方法的最安全方法是什么?

ios - AudioKit 中的点击/失真

ios - 局部变量声明 swift

swift - 无法将类型 '[NSLayoutConstraint]' 的值转换为预期的参数类型 'NSLayoutConstraint'