Search code examples
iosswiftuitableviewheaderuiimageview

How can I add image in UITableView section header using swift?


I have a 4 header. I want to add a image next to the header.

These are my header array;

let sections: [String] = ["Cleaning","Computer Repair", "Electircity", "Painting", "Plumbing"]

How can I add image in UITableView section header using swift?


Solution

  • You have to confirm some UITableViewDataSource and UITableViewDelegate methods.

    To declare number of sections call func numberOfSections(in tableView: UITableView) -> Int method

    To show image in Section Header call func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? method

    If you want to set the height of the section header call func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat method.

    In viewForHeaderInSection method you can design your header. And don't forget to set AutoLayoutConstraint

    You can create an array of UIImage to show image in section header like this

    let sectionImages: [UIImage] = [picutre1, picture2, picture3, picture4]
    

    Here is the full code.

    
    func numberOfSections(in tableView: UITableView) -> Int {
            return sections.count
        }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 80
        }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    
        let imageView = UIImageView()
        imageView.image = sectionImages[section]
        let headerView = UIView()
        headerView.backgroundColor = .white
        headerView.addSubview(imageView)
    
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.centerXAnchor.constraint(equalTo: headerView.centerXAnchor).isActive = true
        imageView.centerYAnchor.constraint(equalTo: headerView.centerYAnchor).isActive = true   
        imageView.heightAnchor.constraint(equalToConstant: 60).isActive = true
        imageView.widthAnchor.constraint(equalToConstant: 60).isActive = true
    
        return headerView
    }