Adding a scrollable header view to a table view

Adding a custom Header View to a Table View in your View Controller

mainView seen in the code below is an instance to the MainView class, MainView is a subclass of a UIView that has the Table View, the table view could have also just been added directly to the View Controller, here this is used for illustration purposes in the case you want to add more UI elements to MainView

mainView.tableView.tableHeaderView = headerView

Setting the frame of the Header View

override init(frame: CGRect) {
  super.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 300))
  commonInit()
}

Completed HeaderView class

class HeaderView: UIView {
  static let reuseIdentifier = "headerView"
  
  public var textLabel: UILabel = {
    let label = UILabel()
    label.text = "Header View"
    label.textAlignment = .center
    label.font = UIFont.preferredFont(forTextStyle: .headline)
    return label
  }()
  
  override init(frame: CGRect) {
    super.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 300))
    commonInit()
  }
  
  required init?(coder: NSCoder) {
    super.init(coder: coder)
    commonInit()
  }
  
  private func commonInit() {
    backgroundColor = .red
    setupLabelConstraints()
  }
  
  private func setupLabelConstraints() {
    addSubview(textLabel)
    textLabel.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
      textLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
      textLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
      textLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8),
      textLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8)
    ])
  }
}

Github Project

Visit Github for the completed project.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s