0

I want two headers at the top of the view controller that does not disappear as the table is scrolled.

The first section of code displays a top header that I have in viewDidLoad. The viewForHeaderInSection works correctly. How do I add the header to the viewForHeaderInSection?

let header =  UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 100))
header.backgroundColor = UIColor.red
//header.addSubview(header)
tableView.tableHeaderView = header

/////////

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let v = UIView()
    v.backgroundColor = UIColor.white

    let segmentControl = UISegmentedControl(frame: CGRect(x: 10, y: 5, width: tableView.frame.width, height: 30))
    segmentControl.insertSegment(withTitle: "one", at: 0, animated: false)
    segmentControl.insertSegment(withTitle: "two", at: 1, animated: false)
    segmentControl.insertSegment(withTitle: "three", at: 2, animated: false)
    v.addSubview(segmentControl)
    return v
}
Charlie Fish
  • 18,491
  • 19
  • 86
  • 179

2 Answers2

0

Just add one view (segmentControl) as a subview of another view (v). And then return that as your view for the viewForHeaderInSection. You have to use constraints between segmentControl & v instances.

And don't forget, for the segmentControl you must set translatesAutoresizingMaskIntoConstraints to false. However you should NOT set translatesAutoresizingMaskIntoConstraints to false for the v instance, because you don't manage the outer constraints for that, the tableview will do it for you...

mfaani
  • 33,269
  • 19
  • 164
  • 293
0

I think this helpful to you:

//Your Tableview

@IBOutlet var tblviewSideMenu: UITableView!

override func viewDidLoad() {  

    super.viewDidLoad()

    let screenSize: CGRect = tblviewSideMenu.frame

    let myView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width,height: 145))
    myView.backgroundColor = UIColor(red: 0.0/255.0, green: 88.0/255.0, blue: 181.0/255.0, alpha: 1.0)

    tblviewSideMenu.addSubview(myView)
    tblviewSideMenu.tableHeaderView = myView
    tblviewSideMenu .reloadData()
    tblviewSideMenu.tableFooterView = UIView()     
 }

Note: if you want two headers add one more view

vinS
  • 1,417
  • 5
  • 24
  • 37