UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: SwiftUI sheet doesn't update content as expected

Forums > SwiftUI

My expectation with the code below is that when a button is tapped, a sheet should appear showing the relevant text.

The issue I'm having is that whichever button is tapped first, when the sheet appears it shows an empty string rather than the updated overlayText value. Dismissing the sheet and tapping the same button has the same result but when I tap a different button, everything starts working as expected.

It seems like SwiftUI is creating the sheet before the overlayText is updated and then ignoring that first update. Does anyone know how to get it to update to the correct info?

I'm still pretty new to Swift (I'm up to day 36 of the 100 Days with SwiftUI course) so I'm hoping this isn't something glaringly obvious. I came across this issue in a bigger app that I was building and was able to replicate it in this simplified example.

import SwiftUI

struct Overlay: View {

    var text: String
    var body: some View {
        Text(text)
    }
}

struct ContentView: View {

    @State private var overlayShowing = false
    @State private var overlayText = ""

    var body: some View {
        Form {

            Button("Button 1") {
                overlayText = "Button 1 was tapped"
                overlayShowing = true
            }
            Button("Button 2") {
                overlayText = "Button 2 was tapped"
                overlayShowing = true
            }
            Button("Button 3") {
                overlayText = "Button 3 was tapped"
                overlayShowing = true
            }
            .sheet(isPresented: $overlayShowing) {
                Overlay(text: overlayText)
            }
        }
    }
}

2      

Try

struct Overlay: View {

    @Binding var text: String
    var body: some View {
        Text(text)
    }
}

and Overlay(text: $overlayText)

I guess you have to remove the private modifier, though.

4      

Thank you so much @Hatsushira. That did the trick and fixed things in the project I was working on too. I still have a lot to learn about bindings and property wrappers…

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.