TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

TabView > List > Sheet State issue

Forums > SwiftUI

Has anyone run into an issue like this before? I think it might actually be a SwiftUI bug. If you have code like the following, when you tap to present the sheet, it will actually fire the onAppear of the sheet view twice when openning and once again when closing:

struct TestView: View {
    var body: some View {
        VStack {
            SubTestView()
        }
    }
}

struct SubTestView: View {
    @State var present: Bool = false

    var body: some View {
        Text("Click me")
            .onTapGesture {
                present = true
            }
            .sheet(isPresented: $present, content: {
                Text("Sheet")
                    .onAppear {
                        print("Sheet presented")
                    }
            })
    }
}

#Preview {
    TabView {
        List {
            TestView()
        }
    }
}

However, if you don't nest the TestSubview in a container (VStack in this case), it will work correctly and only call onAppear once when the sheet appears. Also, to replicate the bug the List must be in a TabView. If you use a ScrollView with a VStack or LazyVStack inside instead of a List it will work correctly.

Something about the combination of TabView, List and the state being pushed down in a subview for the sheet to appear causes the issue. Or am I doing something silly?

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

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.