2

I am trying to programmatically create a button and apply constraints with SnapKit. Everything works fine, but when i apply constraint as make.center.equalTo(self.view) it crashes giving me this message "Terminating app due to uncaught exception Cannot Install Constraint, reason: No common superview between views". Here is my code for creating button:

    func createButton() {
    let button   = UIButton(type: UIButtonType.System) as UIButton
    button.backgroundColor = UIColor.greenColor()
    button.setTitle("Test Button", forState: UIControlState.Normal)
    button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)

    button.snp_makeConstraints { (make) -> Void in
        make.width.equalTo(200)
        make.height.equalTo(70)
        make.center.equalTo(self.view)
    }

    self.view.addSubview(button)
}

1 Answers1

7

The button must be inside a view before you can add constraints.

gnasher729
  • 51,477
  • 5
  • 75
  • 98