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

ale*_*wis 7 swift

我有一个UIButton我在故事板中设置了自动布局约束.我也有一个UIView,我在开始UIViewControllerviewDidLoad方法.我使这个视图具有(几乎)所有相同的属性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)
    }

}
Run Code Online (Sandbox Code Playgroud)

我想我错过了someView.auto布局约束?

编辑:我认为访问UIButton的约束会起作用,但它们似乎是一个空数组.故事板的约束是隐藏的吗?

someView.addConstraints(someButton.constraints)
Run Code Online (Sandbox Code Playgroud)

谢谢.

Rob*_*son 5

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

  • 情节提要中的约束将添加到超级视图中,而不是按钮本身
  • 您尝试复制的约束是引用按钮,而不是新视图

与其复制约束,不如简化约束并创建新约束并引用按钮:

    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)
    ])
Run Code Online (Sandbox Code Playgroud)