Change @State property when another property is changed

Hello, news about SwiftUI have exited me, and I decided to play with it, and seems that I am stuck in primitive stuff, but I haven't really found how to solve it.

struct CellView: View {
    @Binding var color: Int
    @State private var padding : Length = 0

    let colors = [Color.yellow, Color.red, Color.blue, Color.green]
    
    var body: some View {
        colors[color]
            .cornerRadius(20)
            .padding(padding)
            .animation(.spring())
    }
}

and parent view

struct ContentView: View {
    @State private var array: [Int] = [1,2,3]
    
    var body: some View {
            VStack(alignment: .leading) {
                ForEach(self.array.indices) { index in
                    CellView(color: self.$array[index])
                         .tapAction {
                            self.array = [1,1,1]
                         }
                }
           }
    }
}

So basically, when user taps on CellView I am changing colors of every CellView. What I am strugling with, is that I want to add padding animation every time when value of color property is changed for CellView. I want to animate padding from 10 to 0 in this case. But I haven't found a way to somehow "listen" to color property change. I've tried to use didSet in color property and do my manipulations with padding there, but it doesn't work. Am I missing something? Would appreciate any info about this.

Didn’t SwiftUI just change from sending didSet notifications to sending willSet notifications?

I've also tried using willSet, but I believe, that this one does nothing for @Binding property

    @Binding var color: Int {
        willSet {
            print("qwe")
        }
    }

I have investigated more "general" idea of what are you talking about.
How to keep in sync two text fields when you type in one and the result is appearing in another.

Is it what you are looking for?
If so, I built a combined stream of changes of these fields and subscribed on it.

Base64CoderSwiftUI

Have you tried making padding a computed property based on the value of color? I think that would update its value anytime color changes.

1 Like

I can create computed property, but how can I use it to animate padding of view from 10 to 0 not depending of what new color is, every time when color changes?

1 Like

OH, now I see your dilemma. I'm not sure how to do that. From what I can tell, animations can only be applied to a value that is changed, not another value. Transitions give more flexibility, but they only seem to be run when the view is added or removed.

I will be interested to see if you find a solution, or if someone else has any ideas!

This looks like it’s been a useful discussion, but unfortunately I have to say that SwiftUI is generally not on-topic here, and it would be better to ask questions like these on the Apple developer forums.

Terms of Service

Privacy Policy

Cookie Policy