1

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?

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.