Как анимировать привязку дочернего представления - PullRequest
0 голосов
/ 30 мая 2020

Немного запутался, почему этот код не работает должным образом.

Некоторые общие c анимированные представления:

struct SomeAnimatableView: View, Animatable {
    var percent: Double

    var body: some View {
        GeometryReader { geo in
            ZStack {
                Rectangle()
                    .fill(Color.blue)
                    .frame(height: 120)
                Rectangle()
                    .fill(Color.red)
                    .frame(width: geo.size.width * CGFloat(self.percent), height: 116)
            }
            .frame(width: geo.size.width, height: geo.size.height)
        }
    }

    var animatableData: Double {
        set { percent = newValue }
        get { percent }
    }
}

Представления, которые обертывают указанное анимированное представление:

struct ProgressRectangle: View {
    @Binding var percent: Double

    var body: some View {
        SomeAnimatableView(percent: percent)
    }
}

Наконец, еще одно представление, считайте его родительским:

struct ContentView: View {
    @State var percent: Double

    var body: some View {
        VStack {
            ProgressRectangle(percent: $percent.animation())
            Text("Percent: \(percent * 100)")
        }
        .onTapGesture {
            self.percent = 1
        }
    }
}

Проблема ⚠️ почему не анимируется прогресс? $percent.animation() разве это не должно вызывать анимацию? Множество вопросов ...

Исправление ?:

    .onTapGesture {
        withAnimation {
            self.percent = 1
        }
    }

Однако на самом деле это не решает проблему и не отвечает на вопрос, почему эта привязка не анимируется. Поскольку это также, кажется, оживляет весь вид, обратите внимание на кнопку, анимирующую его ширину в этом примере:

An animated image of a progress rectangle growing, starting at the center and expanding outwards towards the right and left. At the bottom, a label with the words: Percent. Followed by the current percent in the animation. The animation loops back to the start when reaching the edges.

Мысли, идеи?

1 Ответ

2 голосов
/ 30 мая 2020

Вот рабочее решение. Протестировано с Xcode 11.4 / iOS 13.4

demo

@State var percent: Double = .zero
var body: some View {
    VStack {
        ProgressRectangle(percent: $percent)
            .animation(.default)            // << place here !!
            .onTapGesture {
                    self.percent = self.percent == .zero ? 1 : .zero
            }
        Text("Percent: \(percent * 100)")
    }
}
...