Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Show/Hide UITableView Header when scrolling up & down?

I have added a HeaderView(from .xib) to UITableView,it is showing properly when i load the ViewController.But how will i hide the tableView Header as i scroll up to any position of tableView and show HeaderView when i scroll down.If anyone could help me it will be appreciated. Below is my code:

class ViewController: UIViewController,UITableViewDataSource,UIScrollViewDelegate {


@IBOutlet var myTable : UITableView!
var array = ["See All Local Deals","Food & Drink","Kids Activities","Taxi" , "Shopping" , "Local Tradesmen" , "Tattoo shop" , "Car Hire" , "Health & Fitness" , "Beauty & Spas" , "Home & Garden" , "Local Services" , "Nightlife" , "Wedding Planning" , "Holiday rentals"]

lazy var headerView : HeaderView? = {
    return Bundle.main.loadNibNamed("HeaderView", owner: self, options: nil)?[0] as? HeaderView

}()

override func viewDidLoad() {
    super.viewDidLoad()

    self.myTable.dataSource = self
  self.myTable.tableHeaderView = headerView

}

func numberOfSections(in tableView: UITableView) -> Int {
 return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return array.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyCell

    cell.lblText.text = array[indexPath.row]
    return cell

}
}
like image 423
anuj Avatar asked Sep 16 '25 02:09

anuj


2 Answers

In storyboard-> Select your tableview-> go with property inspector-> And change type to Grouped from Plain
enter image description here

like image 103
Nishant Bhindi Avatar answered Sep 17 '25 18:09

Nishant Bhindi


In Swift 5.0

The programatic way of doing this is to use UITableView.Style.grouped:

self.tableView = UITableView(frame: .zero, style: .grouped)
like image 30
eharo2 Avatar answered Sep 17 '25 20:09

eharo2