I have a control that sets an @State variable to keep track of the selected tabs in a custom tab View. I can set the @State variable in code by setting the following:
@State var selectedTab: Int = 1
How do I set the initial value programmatically so that I can change the selected tab when the view is created?
I have tried the following:
1:
@State var selectedTab: Int = (parameter == true ? 1 : 2)
2:
init(default: Int) {
self.$selectedTab = default
}
With @State, you tell SwiftUI that a view is now dependent on some state. If the state changes, so should the User Interface. It's a core principle of SwiftUI: data drives the UI.
SwiftUI uses the @State property wrapper to allow us to modify values inside a struct, which would normally not be allowed because structs are value types. When we put @State before a property, we effectively move its storage out from our struct and into shared storage managed by SwiftUI.
Example of how I set initial state values in one of my views:
struct TodoListEdit: View {
var todoList: TodoList
@State var title = ""
@State var color = "None"
init(todoList: TodoList) {
self.todoList = todoList
self._title = State(initialValue: todoList.title ?? "")
self._color = State(initialValue: todoList.color ?? "None")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With