0

I'm a newbie to SwiftUI. I wrote this simple code:

struct ani_repeat: View {
    
    @State private var xv = false
    
    var body: some View {
        VStack {
            Text("Hello, World!")
                .scaleEffect(xv ? 1.5 : 1)
            
            Text("\(xv ? "T" : "F")")
        }
        .onTapGesture {
            withAnimation(Animation.spring().repeatForever()){
                self.xv.toggle()
            }
        }
    }
}

When I first tap the text, it scales repeatedly, and the second line alternates between "T" and "F".

When I tap the text a second time, the first line remains at its original size, but the second line still alternates between "T" and "F".

I don't understand why the first line doesn't scale again, despite toggling xv.

I asked ChatGPT for help, but I still don't understand. My English is not good(for Apple Documents) and I can't buy SwiftUI books where I am.

Blacko
  • 1
  • 1

1 Answers1

0

I tried many ways to solve your problem but many of them failed. I found one solution that is not suitable in certain situations. Here is an example:

import SwiftUI

struct ContentView: View {
    @State private var id: UUID = UUID()
    @State private var xv: Bool = false
    
    var body: some View {
        VStack {
            Text("Hello, World!")
                .scaleEffect(xv ? 1.5 : 1)
            
            Text("\(xv ? "T" : "F")")
        }
        .id(id)
        .onTapGesture {
            if xv {
                id = UUID()
                
                withAnimation(.spring()) {
                    xv = false
                }
            } else {
                withAnimation(.spring().repeatForever()) {
                    xv = true
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I added an .id() modifier for the view that the animation is in. Based on documentation an .id() modifier:

Binds a view’s identity to the given proxy value.

Again based on documentation it means that:

When the proxy value specified by the id parameter changes, the identity of the view — for example, its state — is reset.

So if I click the text a second time, a new id is generated and the view state is reset. This method is kind of like manually resetting the view state. But as I mentioned at the beginning, this approach is not suitable in certain situations.

petomuro
  • 52
  • 10