Swift - Parallax Header View - ScrollView overlap

2019-07-29 13:11发布

问题:

I am trying to custom a extension for Parallax Header. However, it's not working perfectly. The table header view always floats and overlaps cells.

Extension code:

extension UITableView {

  func addImageHeaderView(headerView headerView: UIView, height: CGFloat) {
    self.contentInset = UIEdgeInsetsMake(height, 0, 0, 0)
    self.contentOffset = CGPoint(x: 0, y: -height)
    self.tableHeaderView = headerView
    self.tableHeaderView?.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: height)
  }

  func updateHeaderView(height kTableHeaderHeight: CGFloat) {

    var headerRect = CGRect(x: 0, y: -kTableHeaderHeight , width: self.bounds.width, height: kTableHeaderHeight)
    if self.contentOffset.y < -kTableHeaderHeight {
      headerRect.origin.y = self.contentOffset.y
      headerRect.size.height = -self.contentOffset.y
    }
    self.tableHeaderView?.frame = headerRect
  }

}

Implementing Code :

tableView.addImageHeaderView(headerView: viewHeader, height: 100)

func scrollViewDidScroll(scrollView: UIScrollView) {
      tableView.updateHeaderView(height: 200)
    }

Am I wrong at something? Please show me if you know.

回答1:

Can you please try to set the following in viewDidLoad

self.edgesForExtendedLayout = UIEdgeInsetsZero;

in swift

self.edgesForExtendedLayout = .None

Also what you can try to do is to check the result of the following

tableView.addImageHeaderView(headerView: viewHeader, height: 0)

func scrollViewDidScroll(scrollView: UIScrollView) {
      tableView.updateHeaderView(height: 200)
    }

please notice that i changed the height from 100 to 0 i did it because the height value will change the contentInset of your table view and this is exactly the distance from the top corner