ios - 自动布局前导和尾随约束(动画)

标签 ios animation autolayout constraints

我正在寻找约束行为的解释,基本上我以编程方式创建约束,如下所示:

leadingConstraint = NSLayoutConstraint(item: yellowBlock, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)

trailingConstraint = NSLayoutConstraint(item: yellowBlock, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)

(加上顶部、宽度和高度约束全部设置为常数,但并不真正相关)。然后我要么删除尾随并添加前导,反之亦然,然后调用 UIView 动 Canvas 局IfNeeded()

现在 block 从左向右完美滑动(即最终位置与屏幕的左边缘或右边缘对齐)会发生什么。

现在我想在屏幕边缘添加边距,所以我将前导和尾随约束常量设置为 10 pp。动画期间发生的情况是 block 与左边距 (10 pp) 完全对齐,但是一旦它滑动到右边缘实际上超出了屏幕(通过那 10 页进行侦察)。为什么它会离开屏幕?如果我将前导约束设置为 10,尾随约束设置为(负)-10,那么它就与两侧 10 pp 边距完美对齐。这对我来说毫无意义:(

我确信没有其他限制,甚至尝试重置所有限制,如下所示:

yellowBlock.removeFromSuperview()
yellowBlock.removeConstraints(yellowBlock.constraints())
self.view.addSubview(yellowBlock)
yellowBlock.setTranslatesAutoresizingMaskIntoConstraints(false)

谢谢,

最佳答案

发生这种情况是因为约束具有方向并且在 CSS 中不能用作填充。如果您阅读 constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant: 的文档 您将看到 attr1 是约束左侧的 View 属性。 attr2 用于约束的右侧

因此,您需要设置一个积极因素和另一个消极因素,或者更改 View 和属性的顺序。

关于ios - 自动布局前导和尾随约束(动画),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28293559/

相关文章:

ios - 照片的JPEG NSData转UIImage转JPEG大小完全不同

ios - 如何在cocoapods的版本之间切换?

ios - 如何从 iPad 上的第三方应用程序提取数据?

javascript - JS函数内循环动画

jquery - 如何同时执行多个 jquery 效果?

ios - 片段着色器中的纹理读取

swift - 快速加载时淡入数据

ios - 以编程方式创建 GridView

ios - View 和 super View 之间的 NSSpace 属性必须匹配(自动布局)

iOS 自动布局 : How to move views when label text gets longer