Skip to content

Instantly share code, notes, and snippets.

@zzeleznick
Last active March 6, 2016 23:37
Show Gist options
  • Save zzeleznick/36b4bfa47541f1d7bf50 to your computer and use it in GitHub Desktop.
Save zzeleznick/36b4bfa47541f1d7bf50 to your computer and use it in GitHub Desktop.
A simple function to make buttons programmatically in swift
// MARK: - Storyboard Connections
@IBOutlet weak var letterContainer: UIView! // the UIView that will contain the buttons
// ... stuff
// MARK: Place method call in ViewDidLoad
func makeButtons(content: [String], margin: CGFloat, bottom: CGFloat) {
for i in 0...content.count-1 {
let button: UIButton = UIButton(type: UIButtonType.System)
button.setTitle(content[i], forState: UIControlState.Normal)
// button.setBackgroundImage(UIImage(named: "BlueButton"), forState: UIControlState.Normal)
button.titleLabel?.font = UIFont.systemFontOfSize(12)
button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
// Add buttons to container
letterContainer.addSubview(button)
// Disable Autoresizing constraints
button.translatesAutoresizingMaskIntoConstraints = false
let space: CGFloat = 50.0 + margin
let left: CGFloat = -60.0 + space * CGFloat(i)
// Auto Layout Rules
let leftEdge = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.LeadingMargin, relatedBy: NSLayoutRelation.Equal, toItem: letterContainer, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1.0, constant: left)
let bottomConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: letterContainer, attribute: NSLayoutAttribute.BottomMargin, multiplier: 1.0, constant: bottom)
let heightConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 40)
let widthConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 50)
// Add all constraints
letterContainer.addConstraints([leftEdge, bottomConstraint, heightConstraint, widthConstraint])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment