How to Use the @State Property Wrapper in SwiftUI

Опубликовано: 29 Май 2023
на канале: Julian Michael Technologies
347
19

SwiftUI is fantastic at updating and showing data to the user in realtime. Usually, either the @State or @Published property wrapper is powering this, but today let's focus on @State 😍

@State is a property wrapper, which means it can be added onto a property of a struct like this: @State private var text = ""

Annotating a property with @State tells SwiftUI to redraw the view that contains it every time the property's value changes. For instance, if an image is being fetched from an API and we want to display that image as soon as it's fetched, then it would be a good idea to assign that image to an @State property so that the view is refreshed right after the image is available 🌅

Another common use case for @State is TextFields. You can bind a TextField's text to an @State property like this:

@State private var text = ""

struct ContentView: View {
var body: some View {
TextField("Username", text: $text)
}
}

Now, whenever the user enters text into the TextField, the text value will be updated with whatever text the user entered. This makes it very easy to store the text that the user typed and use it for other purposes like signing into or signing up for an account ✅

🙋‍♂️ When you came across the @State property wrapper for the first time, did you find it confusing? if so, how did you start to understand it? Alternatively, are you having trouble understanding how @State works now? If so, what is stumping you? Let me know down in the comments!

Check out my website here: https://www.julianmichaeltechnologies...

Follow my other socials here:
Instagram:   / jmichaeltech  
TikTok:   / jmichaeltechnologies  
Facebook: https://www.facebook.com/jmichaeltech...
Twitter:   / jmichaeltech  

#shorts