【问题标题】:create UIbutton programmatically with constraints in swift在 swift 中以编程方式创建带有约束的 UIbutton
【发布时间】:2015-04-13 16:04:35
【问题描述】:

提前感谢您的帮助。

我想在每次点击添加按钮时创建一个新的自定义 UIButton。

单击添加按钮后,我希望添加按钮滑过并为新按钮腾出空间。我希望每次都发生这种情况,然后在按钮填满视图的水平空间后创建一个新行

我该怎么做呢?

注意:

我绝对了解如何以编程方式创建按钮,它是让按钮以动画方式滑过的约束/方式,以及我不明白的正确间距

非常感谢你

图片是我想要它的样子的一个快速想法。顶行是我添加几个按钮之前,底行有这么多按钮,需要一个新行

【问题讨论】:

  • 您可以发布一些线框图片来展示您想要的 UI 的外观。
  • 会的。给我一分钟

标签: ios swift uibutton autolayout


【解决方案1】:

您可以通过应用以下代码向任何视图添加约束。

self.view.addConstraints(
  NSLayoutConstraint.constraintsWithVisualFormat(
  "H:|-[myLabel]-|", options: nil, metrics: nil, views: viewsDict))

self.view.addConstraints(
  NSLayoutConstraint.constraintsWithVisualFormat(
  "H:|-[myButton]-|",
  options: nil, metrics: nil, views: viewsDict)) 

self.view.addConstraints(
  NSLayoutConstraint.constraintsWithVisualFormat(
  "V:|-[myLabel]-[myButton]-|", options: nil, metrics: nil, 
  views: viewsDict))

你可以从http://makeapppie.com/2014/07/26/the-swift-swift-tutorial-how-to-use-uiviews-with-auto-layout-programmatically/那里学习一个很好的教程

【讨论】:

  • 太棒了。真的很感激这个
【解决方案2】:

为了能够为视图设置动画,您必须设置约束变量的常量属性(当然,值和方向取决于属性),然后您必须在 UIView 动画块内调用 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。根据你的布局行为,你还需要一个 var 到最后一个按钮,这样你就可以测量位置。

常数0代表约束的初始状态,当它被添加和创建时,因此基于这个初始状态,视图将从它的初始位置移动(从左边开始,或右边或任何初始位置你选)。

我建议您使用类构造函数创建 NSLayoutConstraint 变量,而不是使用可视化语言,因为它会生成一个 NSLayoutConstraints 数组,这使得对一个特定约束的约束检测更加困难。

最后一点:我建议使用 AL 小型库来通过代码更轻松地操作约束,正如您所见,构建 NSLayoutConstraints 可能非常无聊且难以维护。当你使用 Swift 时,请看看这个项目:https://github.com/robb/Cartography

我一直在我的项目中使用它,它对那些情况真的很有帮助。

【讨论】:

  • 太棒了。谢谢你的例子。真的有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-01
  • 1970-01-01
  • 2016-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多