Skip to content

Instantly share code, notes, and snippets.

@natebirkholz
Created August 8, 2021 18:30
Show Gist options
  • Save natebirkholz/1ba6014da563af55e225b3d6a1d61297 to your computer and use it in GitHub Desktop.
Save natebirkholz/1ba6014da563af55e225b3d6a1d61297 to your computer and use it in GitHub Desktop.
class HelloViewController: UIViewController {
let label = UILabel(frame: .zero)
override func viewDidLoad() {
super.viewDidLoad()
label.text = "Hello world!"
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.systemFont(ofSize: 16.0, weight: .medium)
label.textColor = .black
label.textAlignment = .center
label.numberOfLines = 1
label.adjustsFontSizeToFitWidth = true
view.addSubview(label)
setConstraintsForLabel(label)
}
func setConstraintsForLabel(_ constrainedLabel: UILabel) {
guard view.subviews.contains(constrainedLabel) else { return }
let constraints = [
constrainedLabel.heightAnchor.constraint(equalToConstant: constrainedLabel.intrinsicContentSize.height),
constrainedLabel.widthAnchor.constraint(equalTo: view.safeAreaLayoutGuide.widthAnchor, constant: -20.0),
constrainedLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
constrainedLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -40.0)
]
NSLayoutConstraint.activate(constraints)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment