Quick SwiftUI tip for today. If you don’t like that annoying white space a user sees when they scroll past the top of your ScrollView, a Sticky Header works perfectly!

Before getting started, please consider subscribing using this link, and if you aren’t reading this on TrailingClosure.com, please come check us out sometime!

Place this StickyHeader component at the top of a ScrollView and any content you put inside will stretch in size to fill that gap when a user scrolls to the top. See the video below for an example!

struct StickyHeader<Content: View>: View {

    var minHeight: CGFloat
    var content: Content

    init(minHeight: CGFloat = 200, @ViewBuilder content: () -> Content) {
        self.minHeight = minHeight
        self.content = content()
    }

    var body: some View {
        GeometryReader { geo in
            if(geo.frame(in: .global).minY <= 0) {
                content
                    .frame(width: geo.size.width, height: geo.size.height, alignment: .center)
            } else {
                content
                    .offset(y: -geo.frame(in: .global).minY)
                    .frame(width: geo.size.width, height: geo.size.height + geo.frame(in: .global).minY)
            }
        }.frame(minHeight: minHeight)
    }
}

#swift #ios-development

ScrollView Sticky Header
23.50 GEEK