How to add a custom section header to a table view in Swift

by

Two of a simplest approaches is to use delegate method viewForHeaderInSection and return header view in a form of UIView itself or Custom class inheriting UITableViewHeaderFooterView.

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?

Asks the delegate for a view to display in the header of the specified section of the table view.

Using custom header view in the form of just UIView is good when we have something more than text to show in header.


override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView()
    headerView.backgroundColor = UIColor.systemBlue
    return headerView
}

The other way - more flexible - is to have custom class of UITableViewHeaderFooterView. This approach gives much flexibility to have custom states and properties to handle for complex headers. Example code:

You might also like: UIToolbar for keyboard inputAccessoryView gives Layout Constraint Errors


class CustomHeader: UITableViewHeaderFooterView {
    let title = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 40))
    let image = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 40))
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        configureContents()
    }    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
}

Now we register our class, dequeue and return it in viewForHeaderInSection:


tableView.register(CustomHeader.self, forHeaderFooterViewReuseIdentifier: “customSectionHeader”)

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: “customSectionHeader”) as! CustomHeader return headerView }

You might also like: How to Send Local Video to iMessage in Swift

You might also like: AVAudioPlayer not playing any sound

You might also like: How to Get Substring With NSRange in Swift 5

You might also like: Adding two numbers in macOS x86-64 Assembly - Part 2

More Articles

Recommended posts