Swift — How to implement UIButton, UILabel, UITextView and etc programmatically
In this article, I’m going to show you how to implement UIButton, UILabel and etc. without using Storyboard. Sometimes when you want to redesign your app, it’s easier to do it.
let’s create a project.
class ViewController: UIViewController { override func viewDidLoad() {
super.viewDidLoad() }}
Implement Button
Let’s implement UIButton
above override func viewDidLoad()
let cancelButton: UIButton = {
let button = UIButton()
button.setTitle("Cancel".localized, for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 10)
button.backgroundColor = .clear
button.layer.cornerRadius = 10
button.layer.borderWidth = 2
button.layer.borderColor = UIColor.white.cgColor
button.addTarget(self, action: #selector(cancelActionButton), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false return button}()
and add target function when you click the button
@objc func cancelActionButton() {
//your code here when click
}
Implement Label
let yourLabel: UILabel = {
let label = UILabel()
label.text = "your text here"
label.font = UIFont.boldSystemFont(ofSize: 26)
label.textColor = .red
label.translatesAutoresizingMaskIntoConstraints = false
return label}()
Implement TextView
let descriptionTextView: UITextView = {
let textView = UITextView()
let attributeText = NSMutableAttributedString(string: "Learning swift.", attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18)])attributeText.append(NSAttributedString(string: " without using storyboard", attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 12), NSAttributedString.Key.foregroundColor : UIColor.red]))
textView.attributedText = attributeText
textView.textAlignment = .center
textView.isEditable = false
textView.isScrollEnabled = false
textView.translatesAutoresizingMaskIntoConstraints = false
return textView}()
Implement View
let blueView: UIView = {
let view = UIView()
view.backbgroundColor = .blue
view.translatesAutoresizingMaskIntoConstraints = false
return view}()
So let’s set up the layout, Create a function, and set up your layout here.
private func setupLayout() {}
Example: Set up blueView
private func setupLayout() { blueView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
blueView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true blueView.heightAnchor.constraint(equalToConstant: 50).isActive = true
blueView.widthAnchor.constraint(equalTo: doneButton.widthAnchor).isActive = true}
Add this function to override func viewDidLoad()
, and add blueView
to view
override func viewDidLoad() {
super.viewDidLoad() view.addSubview(blueView)
setupLayout()}