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

ios, swift, uitableview

Solution

You could design your own header, like you would design a custom cell in a table view. Or you could just add an image like so:

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

    var myCustomView: UIImageView
    var myImage: UIImage = UIImage(named: "myImageResource")
    myCustomView.image = myImage

    let header: UITableViewHeaderFooterView = view as UITableViewHeaderFooterView
    header.addSubview(myCustomView)
    return header
}

Then you can simply add your section title UILabel as another subview.

Problem

In my willDisplayHeaderView I have changed color of section header But I want to add an image before section title. Any help? My code for willDisplayHeaderView is ``` func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as UITableViewHeaderFooterView header.contentView.backgroundColor = UIColor(red: 238/255, green: 168/255, blue: 15/255, alpha: 0.8) header.textLabel.textColor = UIColor.whiteColor() header.alpha = 1 } ```

Original source