How to make a Stretchy Header in iOS using Swift

Stretchy Top Cell

In this tutorial, I’ll show you step by step how to a stretchy header in TableView, CollectionView, and ScrollView Example.

Simple, Strongly Typed UserDefaults for iOS, macOS and tvOS.

Stretchy Header


Creating a sticky and stretchy top cell consists of a good way to override the default tableview behaviour and make your UI look definitely cool. You might be thinking that it’s a complicated effect to achieve, but no, it’s not! Believe it or not, the actual code that creates the trick is taking up three lines of code only. Nowadays, several apps offer this effect, so why not yours as well?

In this short tutorial I’m going to show how to achieve the previous effect using two different approaches. So, just read on!

You can find those two approaches I’m discussing next as a gist here as well.

Approach #1

Implement the following scroll view delegate method:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView.contentOffset.y < 0.0 {
        if let cell = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) {
            cell.frame.origin.y = scrollView.contentOffset.y
            let originalHeight: CGFloat = 280.0            
            cell.frame.size.height = originalHeight + scrollView.contentOffset.y * (-1.0)
        }
    }
}

Approach #2

Declare the following property in your class:

var lastContentOffset = CGPoint.zero
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView.contentOffset.y < 0.0 {
        if let cell = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) {
            let deltaY = CGFloat(fabsf(Float(scrollView.contentOffset.y)) - fabsf(Float(lastContentOffset.y)))            
            cell.frame = CGRect(x: 0.0, y: scrollView.contentOffset.y, width: cell.frame.size.width, height: cell.frame.size.height + deltaY)
            lastContentOffset = scrollView.contentOffset
        }
    }
}

Download

Stretchy

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *