首页 文章

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

提问于
浏览
0

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

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动画layoutIfNeeded()

现在,块从左到右完美地滑动(即最终位置与屏幕的左边缘或右边缘对齐) .

现在我想在屏幕的边缘添加边距,所以我将前导和尾随约束设置为10 pp . 在动画期间发生的是块完全对齐到左边距(10 pp),但是一旦它滑到右边缘它实际上超越了屏幕(重新调整了10页) . 为什么它会关闭屏幕?如果我将前导约束设置为10,并且尾随(减去)-10,那么它的两侧都是10 pp边距 . 这对我没有意义:(

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

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

谢谢,

1 回答

  • 1

    发生这种情况是因为约束具有方向,并且不能用作CSS中的填充 . 如果您阅读constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:的文档,您将看到attr1是约束的 left hand side 视图的属性 . attr2用于约束的 right hand side .

    因此,您需要设置一个正面和另一个负面或更改视图和属性的顺序 .

相关问题