Matt Braniff
Matt Braniff

Reputation: 107

SwiftUI updating class sub variables

I want an easy way to update UI state with the use of a single state variable. Lets say I have a class Position that instance variables x and y. Imagine I have a UI view that looks something like this...

@State var position: Position
var body: some View{
    VStack{
        Text("x: \(position.x)")
        Text("y: \(position.y)")
    }
}

I would like to maintain a single state variable of Position that can update both the x and y like shown above. But, as you may know this code will not update the x and y values on the UI View if they do change inside this position variable.

Does anyone know a way to update this view everytime x and y changes without having to have individual State variables for both x and y or is this the only way?

Upvotes: 1

Views: 202

Answers (1)

Asperi
Asperi

Reputation: 258541

Does anyone know a way to update this view everytime x and y changes without having to have individual State variables for both x and y or is this the only way?

The Position should be struct to have behaviour as you need, like

struct Position {
  var x: CGFloat
  var y: CGFloat
}

in such case whenever any of x/y changed the single @State var position will update the view.

Upvotes: 1

Related Questions