Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom header content animate while scrolling in swift

I have created custom header but I don't know how to animate while scrolling.

Please check below image and let me know how to animate while scrolling. This animated header in Fotmob app.

enter image description here

like image 522
Vivek Avatar asked Dec 07 '25 09:12

Vivek


1 Answers

First of all add header view as UIvVew and add UIScrollView or UITableView below headerView same as screenshot and follow below step.

enter image description here

  1. set a fixed height constraint to the header view (125 for example) and attach it to top, left and right.

  2. make the UIScrollView below to use all the available space so set to zero top, bottom, left and right constraints.

  3.  connect the header view height constraint to the ViewController in order to have something like:

     @IBOutlet var headerViewHeightConstraint: NSLayoutConstraint!
    
  4. set the UIScrollView delegate to the ViewController

  5. declare two properties to limit the maximum and the minimum height of the header view, fox example:

    let headerViewMaxHeight: CGFloat = 125
    let headerViewMinHeight: CGFloat = 44 + UIApplication.shared.statusBarFrame.height
    
  6. The entire workaround is based on update the header view height constraint while the UIScrollView is scrolling, so let’s implement the UIScrollViewDelegate and the most important delegate for our case, the scrollViewDidScroll:

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
    
        let headerViewMinHeight: CGFloat = 44 + UIApplication.shared.statusBarFrame.height
    
        let yPos = mainScrollView.contentOffset.y
        let newHeaderViewHeight: CGFloat = headerViewHeightConstraint.constant - yPos
    
        if newHeaderViewHeight > headerViewMaxHeight {
            // Here, Manage Your Score Format View
            headerViewHeightConstraint.constant = max(headerViewMaxHeight, newHeaderViewHeight)
    
        } else if newHeaderViewHeight < headerViewMinHeight {
    
        headerViewHeightConstraint.constant = headerViewMinHeight
    
        } else {
    
            headerViewHeightConstraint.constant = newHeaderViewHeight
            scrollView.contentOffset.y = 0 // block scroll view
    
        }
    }
    
like image 69
skety777 Avatar answered Dec 10 '25 01:12

skety777



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!