user3069232
user3069232

Reputation: 8995

Animation works the first time, but then

Trying to animate a SwiftUI view. Works perfectly the first time, but then does nothing.
self.pressed starts out as false. I set it to true and then I switch it back to false.
I want to scale it up and then scale it back it down on button press.

What am I missing here?

Button(action: {
    withAnimation(.linear(duration: 3)) {
        self.pressed = true
    }
    withAnimation(.linear(duration: 3)) {
        self.pressed = false
    }
}) {
    Wedge(startAngle: .init(degrees: 270), endAngle: .init(degrees: 360))
        .fill(Color.green)
        .frame(width: 200, height: 200)
        .offset(x: -100, y: 100)
        .scaleEffect(self.pressed ? 1.2 : 1.0)
}

Basically it resizes my wedge shape when I press it, but then does nothing the next time I press it.

I did get it work with DispatchQueue, but it seems like a hack:

Button(action: {
    withAnimation(.linear(duration: 0.5)) {
        self.pressed = !self.pressed
    }
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
        withAnimation(.linear(duration: 0.5)) {
            self.pressed = !self.pressed
        }
    }
}) {
    Wedge(startAngle: .init(degrees: 180), endAngle: .init(degrees: 270))
        .fill(Color.red)
        .frame(width: 200, height: 200)
        .offset(x: 80, y: 80)
        .scaleEffect(self.pressed ? 1.2 : 1.0)
}

Is the second way the right way to do this?

--

Here is Wedge:

struct Wedge: Shape {
    let startAngle: Angle
    let endAngle: Angle

    func path(in rect: CGRect) -> Path {
        var path = Path()
        let center = CGPoint(x: rect.midX, y: rect.midY)
        path.addArc(center: center,
                    radius: min(rect.midX, rect.midY),
                    startAngle: startAngle,
                    endAngle: endAngle,
                    clockwise: false )
        path.addLine(to: center)
        path.closeSubpath()
        return path
    }
}

Upvotes: 1

Views: 252

Answers (1)

Asperi
Asperi

Reputation: 258345

Probably you wanted this

Button(action: {
    withAnimation(.linear(duration: 3)){
      self.pressed.toggle()               // << here !!
    }
    print("B")
    }) {
 ...

Upvotes: 1

Related Questions