UITableView Section Background?

Viewed 7998

Is it possible to have a background image used behind a section in a UITableView?

I can't think of how to achieve this.

3 Answers

To add background image behind section in UITableView so that it scrolls, write in viewDidAppear

let frame = tableView.rect(forSection: 0)
let view = UIView(frame: frame)
let imgView = UIImageView(frame: view.bounds)

// Assign image here ...

view.addSubview(imgView)

tableView.addSubview(view)
tableView.sendSubviewToBack(view)

NOTE: Keep the background color of table view cells clear so that background view is visible

Swift 5
write the following code after update data in the table view :

        let frame = tableView.rect(forSection: 0)
        let backgroundView = UIView(frame: frame)
        let imageView = UIImageView(frame: view.bounds)
        imageView.image = your image
        backgroundView.addSubview(imageView)
        tableView.addSubview(backgroundView)
        tableView.sendSubviewToBack(backgroundView)
        tableView.backgroundColor = .clear

After that , you will need to bring the cells to the front in willDisplaycell method as the following :

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        tableView.bringSubviewToFront(cell)
}
Related