How do I set an @State variable programmatically in SwiftUI

Viewed 10868

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
}
3 Answers

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")
    }

Joe Groff: "@State variables in SwiftUI should not be initialized from data you pass down through the initializer. The correct thing to do is to set your initial state values inline:"

@State var selectedTab: Int = 1

You should use a Binding to provide access to state that isn't local to your view.

@Binding var selectedTab: Int

Then you can initialise it from init and you can still pass it to child views.

Source: https://forums.swift.org/t/state-messing-with-initializer-flow/25276/3

This was so simple to solve once I discovered the answer!

You simply remove the initial value from the initialization by changing the declaration from:

@State var selectedTab: Int = 1

to:

@State var selectedTab: Int

and then the selectedTab variable automatically becomes a parameter in the instantiation statement. So the initialization would be:

TabBarContentView(selectedTab: 2)

Its that simple!!!!!

Related