swift - 显示具有编程约束的按钮

标签 swift uiview uibutton xcode8 ios10

尽管为我的按钮添加了对前导 anchor 和顶部 anchor 的约束(我试图将它们显示在列表中),但 View 将所有它们显示在 View 的左上角。我正在调用许多方法来尝试应用约束,但它们似乎都不起作用。救命!

func displayButtonArray(buttons: [UIButton]) {
    var previousButton: UIButton = buttons[0]
    for (i, button) in buttons.enumerated() {
        button.setTitle("SampleButton", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.sizeToFit()

        let margins = self.view.layoutMarginsGuide
        button.leadingAnchor.constraint(equalTo: margins.leadingAnchor)
        if i == 1 {
            button.topAnchor.constraint(equalTo: margins.topAnchor, constant: CGFloat(5.0))
        } else {
            button.topAnchor.constraint(equalTo: previousButton.bottomAnchor, constant: CGFloat(10.0))
        }
        previousButton = button

        button.translatesAutoresizingMaskIntoConstraints = false
        button.setNeedsUpdateConstraints()
        button.setNeedsLayout()

        self.view.addSubview(button)
    }
    self.view.setNeedsUpdateConstraints()
    self.view.setNeedsLayout()
    self.view.layoutSubviews()
}

最佳答案

正如您所指出的,约束已定义但未激活。

我可以补充的一件事是,正如 Apple 所提到的,自动布局约束应该一起激活。

您可以逐一激活它们,但一起激活它们的效率更高;从而获得更好的性能。

关于swift - 显示具有编程约束的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41529669/

相关文章:

ios - 应用程序文档目录在构建时发生变化

ios - 以编程方式创建 UIButton 比使用 Storyboard 模糊

ios - 如何在 iOS 中平滑地放大和缩小 UIButton

ios - RxSwift 使用 bindTo 将 Variable<String> 绑定(bind)到 UILabel 不适用于 Swift 3.0 更新

ios - 如何将获取的ObjectID与字符串进行比较?

objective-c - 在 UIView 之间拖动 UIView

ios - 在 UIView 上使用 CAGradientLayer 绘制渐变不起作用

ios - 圆形 UIButton 中的文本未居中对齐 - Objective C

ios - 如何将 subview 添加到自定义 UICollectionViewCell

ios - UIView滑动过渡淡出