我正在努力更新/简化我关于自动布局与 NSConstraints 的代码,但现在似乎让我感到困惑。
我有一些 Swift 3 代码,可以在轻按按钮时在 UIView 中滑动,但是 UIView 由 NSconstraints 控制并且工作正常。 -
@IBAction func rightFlyOutButton(_ sender: Any) {
if (rightFlyOutShowing) {
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
leftFlyOutLeadingConstraint.constant = 25
} else {
leftFlyOutLeadingConstraint.constant = 15
}
rightFlyOutTrailingConstraint.constant = rightFlyOut.frame.width * 0.93
UIView.animate(withDuration: 0.4, animations: {self.view.layoutIfNeeded()})
} else {
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
rightFlyOutTrailingConstraint.constant = 25
} else {
rightFlyOutTrailingConstraint.constant = 15
}
UIView.animate(withDuration: 0.4, animations: {self.view.layoutIfNeeded()})
}
rightFlyOutShowing = !rightFlyOutShowing
}
尝试使用 AutoLayout 和 Layout Anchors,我想到了这个 -
@IBAction func rightFlyOutButton(_ sender: Any) {
rightFlyOut.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
rightFlyOut.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.93).isActive = true
UIView.animate(withDuration: 0.4, animations: {self.view.layoutIfNeeded()})
}
这会返回大量错误 -
[LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSAutoresizingMaskLayoutConstraint:0x6000000949b0 h=-&& v=-&& FasteM.UIViewX:0x7fed7140c600.width == 0.500741*UIView:0x7fed7161d760.width + 150.222 (active)>",
"<NSLayoutConstraint:0x6000000900e0 FasteM.UIViewX:0x7fed7140c600.width == 0.93*UIView:0x7fed7161d760.width (active)>",
"<NSLayoutConstraint:0x600000095a90 'UIView-Encapsulated-Layout-Width' UIView:0x7fed7161d760.width == 375 (active)>"
)
我的逻辑是我将 View 的右边缘锚定到父 View 并指定实际 View 的宽度(即父 View 的 93%。
我确信这是我遗漏的一个简单错误,但我将不胜感激任何指向正确方向的指示。
TIA
最佳答案
第二种方法的问题是每次点击都会创建其他约束,这会与旧的相同约束发生冲突,因此您应该在任何地方创建这些约束,获取对它们的引用并在您更改它们的常量时以最正确的方式做
关于ios - Swift 4 中的布局 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49136711/