Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set an @State variable programmatically in SwiftUI

Tags:

swiftui

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
}
like image 766
J. Edgell Avatar asked Jun 14 '19 05:06

J. Edgell


People also ask

What does @state do in SwiftUI?

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.

What is the @state attribute in Swift?

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.


1 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")
    }
like image 70
stardust4891 Avatar answered Sep 20 '22 10:09

stardust4891