custom view programatically with a label and a button in swift

To create a custom UIView with a UILabel and a UIButton programatically, follow these steps:

  1. Create a new class CustomView that extends UIView
main.swift
class CustomView: UIView {
  
}
32 chars
4 lines
  1. Declare and initialize UI components, UILabel and UIButton using UILabel() and UIButton(type: ) respectively inside the CustomView class
main.swift
class CustomView: UIView {
  
  let label = UILabel()
  let button = UIButton(type: .system)
  
}
98 chars
7 lines
  1. In the init method, configure the properties of UI components
main.swift
class CustomView: UIView {
  
  override init(frame: CGRect) {
    super.init(frame: frame)
    configureLabel()
    configureButton()
  }
  
  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  
  private func configureLabel() {
    label.text = "Custom View Label"
    label.textColor = .black
    label.textAlignment = .center
    addSubview(label)
    // Configure label constraints
  }
  
  private func configureButton() {
    button.setTitle("Custom View Button", for: .normal)
    button.backgroundColor = .green
    button.setTitleColor(.white, for: .normal)
    addSubview(button)
    // Configure button constraints
  }
  
}
689 chars
30 lines
  1. Set constraints for the UI components inside the CustomView
main.swift
private func configureLabel() {
    ...
    addSubview(label)
    
    label.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        label.centerXAnchor.constraint(equalTo: self.centerXAnchor),
        label.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: -20),
        label.widthAnchor.constraint(equalToConstant: 200),
        label.heightAnchor.constraint(equalToConstant: 30)
    ])
}

private func configureButton() {
    ...
    addSubview(button)
  
    button.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        button.centerXAnchor.constraint(equalTo: self.centerXAnchor),
        button.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 20),
        button.widthAnchor.constraint(equalToConstant: 200),
        button.heightAnchor.constraint(equalToConstant: 40)
    ])
}
885 chars
26 lines

Now, you can add this CustomView to any UIView as a subview and it will display a UILabel and UIButton.

main.swift
let customView = CustomView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
view.addSubview(customView)
108 chars
3 lines

This will display a CustomView with a UILabel and a UIButton on top of it.

gistlibby LogSnag