预先感谢您的帮助。
我想在每次单击“添加”按钮时创建一个新的自定义 UIButton。
单击添加按钮后,我希望添加按钮滑过并为新按钮腾出空间。我希望每次都发生这种情况,然后在按钮填满 View 的水平空间后创建一个新行
我怎么会这样做?
注意:
我完全理解如何以编程方式创建按钮,它是让按钮动画滑过的约束/方式,以及我不理解的正确间距
非常感谢
图像是我希望它看起来像什么的快速概念。顶行是在我添加几个按钮之前,底行有太多按钮需要新一行
最佳答案
为了能够为 View 设置动画,您必须设置约束变量的常量属性(当然,值和方向取决于属性),稍后您必须在 UIView 动画 block 中调用 layoutIfNeeded() .
代码示例:
...
let newButton = UIButton()
containerView.addSubview(newButton)
...
// after adding the button
let horizontalSpace = ButtonWidth + horizontalSpace * 2
let newLeft = lastButtonX + 2 * (buttonWidth + horizontalSpace) + horizontalSpace
let newLeftConstraint = NSLayoutConstraint(item: newButton, attribute: .Left, relatedBy: .Equal, toItem: lastButton, attribute: .Right, multiplier: 0, constant: horizontalInset)
lastButton = newButton
if newLeft + addButtonWidth >= screenWidth {
containerView.layoutIfNeeded()
addButtonLeftConstraint.constant = horizontalSpace
addButtonTopConstraint.constant = buttonRowsNumber * rowHeight + verticalSpace
UIView.animateWithDuration(animationTime) {
containerView.layoutIfNeeded()
}
} else {
containerView.layoutIfNeeded()
addButtonLeftConstraint = newLeft
UIView.animateWithDuration(animationTime) {
containerView.layoutIfNeeded()
}
}
注意事项:
您需要为以后要设置动画的每个约束保留一个变量。根据您的布局行为,您还需要一个指向最后一个按钮的 var,以便您可以测量位置。
常量 0 表示约束的初始状态,当它被添加和创建时,所以基于这个初始状态, View 将从它的初始位置(从左边开始,或右边或任何初始位置)移动你选)。
我建议您使用类构造函数而不是使用视觉语言来创建 NSLayoutConstraint 变量,因为它会生成一个 NSLayoutConstraints 数组,这使得对一个特定约束的约束检测变得更加困难。
最后一点:我建议使用一个 AL 小型库来通过代码更轻松地操纵约束,如您所见,构建 NSLayoutConstraints 可能非常乏味且难以维护。当您使用 Swift 时,请看一下这个项目:https://github.com/robb/Cartography
我一直在我的项目中使用它,它对那些情况真的很有帮助。
关于ios - 以编程方式快速创建带有约束的 UIbutton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28485621/