Skip to content

Instantly share code, notes, and snippets.

@C-Rodg
Created May 16, 2018 23:43
Show Gist options
  • Save C-Rodg/4c509c8ce8ff9ab196e33117bff00853 to your computer and use it in GitHub Desktop.
Save C-Rodg/4c509c8ce8ff9ab196e33117bff00853 to your computer and use it in GitHub Desktop.
A sample of programmatically assign constraints to a UIButton in Swift.
import UIKit
class ViewController: UIViewController {
struct LayoutProperties {
static let sideSpacing: CGFloat = 20
static let cornerRadius: CGFloat = 8
static let buttonHeight: CGFloat = 60
}
private let subscribeButton: UIButton = {
let b = UIButton(type: .system)
b.translatesAutoresizingMaskIntoConstraints = false
b.setTitle("MY FAVORITE BUTTON", for: .normal)
return b
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(subscribeButton)
subscribeButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: LayoutProperties.sideSpacing).isActive = true
subscribeButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
subscribeButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
subscribeButton.heightAnchor.constraint(equalToConstant: LayoutProperties.buttonHeight).isActive = true
styleUIComponents()
}
private func styleUIComponents() {
subscribeButton.layer.cornerRadius = LayoutProperties.cornerRadius
subscribeButton.backgroundColor = UIColor.red
subscribeButton.setTitleColor(.white, for: .normal)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment