Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save PraveenKommuri/f67e15a5849a2ca848b9de6ff2549f84 to your computer and use it in GitHub Desktop.
Save PraveenKommuri/f67e15a5849a2ca848b9de6ff2549f84 to your computer and use it in GitHub Desktop.
Programmatically creating UIButton & set the constraints in code. Setting the button in middle of the screen for box x&y axis.
let takeVideoButton = UIButton(type: .system)
//takeVideoButton.frame = CGRect(x: 30, y: 30, width: 100, height: 50)
takeVideoButton.setTitle("Take Video", for: .normal)
takeVideoButton.addTarget(self, action: #selector(takeVideo), for: .touchUpInside)
self.view.addSubview(takeVideoButton)
takeVideoButton.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraint = NSLayoutConstraint(item: takeVideoButton, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)
let verticalConstraint = NSLayoutConstraint(item: takeVideoButton, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0)
let widthConstraint = NSLayoutConstraint(item: takeVideoButton, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1, constant: 100)
let heightConstraint = NSLayoutConstraint(item: takeVideoButton, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 1, constant: 100)
NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint, widthConstraint, heightConstraint])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment