How to add a view over UITableView that scrolls, but go up after scrolling

advertisements

I have a UIView with height of 100 pixels that's on top of my UITableView. When I scroll up I want the UIView to scroll together with my UITableView as if it's part it. When 50 pixels of my UIView is hidden from scrolling up, I want to pin the UIView at the top while I continue scrolling up. How can this be achieved? I tried using changing my UIView's top NSLayoutConstraint constant equal to my tableview's content offset, but they don't scroll at the same speed.


First make sure your tableView is grouped:

self.tableView = UITableView(frame: CGRect(x: 0, y: (self.navigationController?.navigationBar.frame.maxY)!, width: self.view.bounds.size.width, height: (self.view.bounds.size.height - (self.navigationController?.navigationBar.frame.maxY)!)), style: .grouped)
self.tableView.delegate = self
self.tableView.dataSource = self
self.view.addSubview(self.tableView)

Then you need to add the UIView into the subview of your tableView:

self.myView = UIView()
self.myView.backgroundColor = UIColor.green
self.myView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 100)
self.tableView.addSubview(self.myView)

Add a header of height 100 for your tableView's first section so that your cells are at right place:

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

Then adjust the frame of your UIView when scrolling:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let offset = scrollView.contentOffset.y
    if(offset > 50){
        self.myView.frame = CGRect(x: 0, y: offset - 50, width: self.view.bounds.size.width, height: 100)
    }else{
        self.myView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 100)
    }
}

Demo: