FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

SOLVED: How can I make a ScrollView cover a Text when scrolling

Forums > SwiftUI

Hi,

I'm trying to have a screen composed of two things: a Text at the top and bellow the Text a ScrollView, and the Text should disappear when scrolling, hidden behind the ScrollView.

This is a pseudo solution that I have found:

ScrollView {
    Text("This is a text view")
    ScrollView {
        VStack(spacing: 20) {
            ForEach(0..<50) {
                Text("Item \($0)")
            }
        }
    }
}

This makes the Text disappear when scrolling but it isn't hidden behind the ScrollView, this is how I'd like it to look like: gif of how it should look like

   

The best way to overlap views in SwiftUI is to use a ZStack.

This is some code that I have tested with, and that works:

ZStack(alignment: .top) {
  Text("This is a text view")
    .background(Color.red)

    ScrollView {
      VStack(spacing: 20) {
        ForEach(0..<50) {
          Text("Item \($0)")
        }
      }
      .background(Color.blue)
      .padding(.top, 40) // can change this
    }
}

The padding applied to the VStack is so that the scrolling content originally stays below the static text view. I wouldn't recommend keeping it like this since you don't know how high the text view always is. There are many more efficient and reuasble alternatives, such as custom alignment guides, but I'll leave that solution up to you.

   

Thank you very much for your help, that was exactly what I was looking for! :)

   

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for iOS devs who want to become complete senior developers — from October 18th to 24th. Learn how to apply iOS app architecture patterns through a series of lectures and practical coding sessions.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.