Is it possible to extend a table header view so that it goes behind the first row of cells like a background?

159 Views Asked by At

There are 2 different versions of app, one with the table header view on top of the cells. The other version it's supposed to extend behind the first row of cells like a background, but still maintain its same starting position on top of the rows. Is this even possible? If not suggestions are welcome on how to create this type of effect.

This is the effect I'm trying to go for: enter image description here

1

There are 1 best solutions below

2
Fabio On

Try this: set containerView object:

let tableBgView = UIView()

after that set your dummy header view:

let bgCell = UIView()

Now set tableView background color to .clear

tableView.backgroundColor = .clear

In cellForRowAt (or in your custom cell) set cell backgroundColor to .clear

cell.backgroundColor = .clear

In viewDidLoad set you objects property and tableView background view:

tableBgView.backgroundColor = .white
tableBgView.frame = view.bounds

bgCell.backgroundColor = .yourColor
bgCell.translatesAutoresizingMaskIntoConstraints = false
tableBgView.addSubview(bgCell)

now set auto layout of bgCell:

bgCell.topAnchor.constraint(equalTo: tableBgView.topAnchor).isActive = true
bgCell.leadingAnchor.constraint(equalTo: tableBgView.leadingAnchor).isActive = true
bgCell.trailingAnchor.constraint(equalTo: tableBgView.trailingAnchor).isActive = true
bgCell.heightAnchor.constraint(equalToConstant: yourCellHeight).isActive = true

add tableView bacgroundView:

tableView.backgroundView = tableBgView

This is the result:

enter image description here

Update

if you want tableView header too simply add:

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 70
}

and create your tableViewHeader:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let myView = UIView()
    myView.backgroundColor = .yourColor
    
    let label = UILabel()
    label.text = "Header"
    label.textColor = .white
    label.font = .systemFont(ofSize: 20, weight: .semibold)
    label.textAlignment = .center
    label.translatesAutoresizingMaskIntoConstraints = false
    
    myView.addSubview(label)
    label.topAnchor.constraint(equalTo: myView.topAnchor).isActive = true
    label.leadingAnchor.constraint(equalTo: myView.leadingAnchor).isActive = true
    label.trailingAnchor.constraint(equalTo: myView.trailingAnchor).isActive = true
    label.bottomAnchor.constraint(equalTo: myView.bottomAnchor).isActive = true
    
    return myView
}

And this is the result:

enter image description here

For image see the comment below..

enter image description here