Swift:以编程方式将自动布局约束从一个视图复制到另一个视图

9

我有一个UIButton,在storyboard中使用自动布局约束设置。我还在UIViewControllerviewDidLoad方法中初始化了一个UIView。我使这个视图具有与UIButton几乎相同的属性,但是当我在模拟器中运行它时,它不会“粘”在按钮上。以下是我的代码:

class ViewController: UIViewController {

    @IBOutlet weak var someButton: UIButton!

    func viewDidLoad() {
        super.viewDidLoad()

        let someView = UIView()
        someView.backgroundColor = UIColor.greenColor()
        someView.frame = someButton.bounds
        someView.frame.origin = someButton.frame.origin
        someView.autoresizingMask = someButton.autoresizingMask
        someView.autoresizesSubviews = true
        someView.layer.cornerRadius = someButton.layer.cornerRadius
        someView.clipsToBounds = true
        someView.userInteractionEnabled = false
        view.insertSubview(someView, belowSubview: someButton)
    }

}

我想我可能忘记了someView的自动布局约束? 编辑:我以为访问UIButton的约束会起作用,但它们似乎是一个空数组。难道故事板约束被隐藏了吗?
someView.addConstraints(someButton.constraints)

谢谢。

1个回答

6

以这种方式复制约束会失败,因为:

  • Storyboard 中的约束被添加到父视图中而不是按钮本身
  • 尝试复制的约束引用的是按钮而不是您的新视图

不要复制约束,保持简单并创建新的约束并引用按钮:

    let someView = UIView()
    someView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(someView)

    view.addConstraints([
        NSLayoutConstraint(item: someView, attribute: .Leading, relatedBy: .Equal, toItem: someButton, attribute: .Leading, multiplier: 1, constant: 0),
        NSLayoutConstraint(item: someView, attribute: .Trailing, relatedBy: .Equal, toItem: someButton, attribute: .Trailing, multiplier: 1, constant: 0),
        NSLayoutConstraint(item: someView, attribute: .Top, relatedBy: .Equal, toItem: someButton, attribute: .Top, multiplier: 1, constant: 0),
        NSLayoutConstraint(item: someView, attribute: .Bottom, relatedBy: .Equal, toItem: someButton, attribute: .Bottom, multiplier: 1, constant: 0)
    ])

你能从父视图中访问按钮的约束吗?我非常喜欢控件拖拽 :-) - ajrlewis
你可以这样做,但为什么要选择那种方式呢?基本上,你需要循环遍历父视图的约束,并将firstItem和secondItem与按钮进行比较。虽然这不是特别安全的方法。 - Robert Gummesson
你是对的,我猜我只是认为通过手动操作能够获得更加精确的结果。我需要修正我的自动布局。 - ajrlewis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接