How do I update a text label in SwiftUI?

With only the code you shared it is hard to say exactly how you should do it but here are a couple good ways:

The first way is to put the string in a @State variable so that it can be mutated and any change to it will cause an update to the view. Here is an example that you can test with Live Previews:

import SwiftUI

struct UpdateTextView: View {
    @State var textToUpdate = "Update me!"
    var body: some View {
        VStack {
            Button(action: {
                self.textToUpdate = "I've been udpated!"
            }) {
                Text("SignUp")
            }
            Text(textToUpdate)
        }
    }
}

struct UpdateTextView_Previews: PreviewProvider {
    static var previews: some View {
        UpdateTextView()
    }
}

If your string is stored in a class that is external to the view you can use implement the ObservableObject protocol on your class and make the string variable @Published so that any change to it will cause an update to the view. In the view you need to make your class variable an @ObservedObject to finish hooking it all up. Here is an example you can play with in Live Previews:

import SwiftUI

class ExternalModel: ObservableObject {
    @Published var textToUpdate: String = "Update me!"
    func registerRequest() {
        // other functionality
        textToUpdate = "I've been updated!"
    }
}

struct UpdateTextViewExternal: View {
    @ObservedObject var viewModel: ExternalModel
    var body: some View {
        VStack {
            Button(action: {
                self.viewModel.registerRequest()
            }) {
                Text("SignUp")
            }
            Text(self.viewModel.textToUpdate)
        }
    }
}

struct UpdateTextViewExternal_Previews: PreviewProvider {
    static var previews: some View {
        UpdateTextViewExternal(viewModel: ExternalModel())
    }
}

Tags:

Ios

Swift

Swiftui