Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update a text label in SwiftUI?

Tags:

ios

swift

swiftui

I have a SwiftUI text label and i want to write something in it after I press a button.

Here is my code:

Button(action: {
                registerRequest() // here is where the variable message changes its value
            }) {
                Text("SignUp")
            }
            Text(message) // this is the label that I want to change

How do I do this?

like image 832
Susca Bogdan Avatar asked Mar 18 '20 16:03

Susca Bogdan


People also ask

How do I update TextField in SwiftUI?

To fix that all you need to do is set a style for your TextField with the . textFieldStyle modifier. Now you should see a rounded border around your text field! You can find a list of all of the available text field styles in Apple's documentation here.


1 Answers

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())
    }
}
like image 85
Helam Avatar answered Sep 20 '22 07:09

Helam