ios – SwiftUI’s .contentTransition(.numericText()) not working as expected when using .onChange modifier?


I’m trying to implement SwiftUI’s new .contentTransition(.numericText()) as described in this post. But I can’t figure out why it works on a button tap, but I can’t get it to work where I need, in an .onChange modifier? 🤔

struct ContentView: View {
    @State private var newNumberForAnimation = 98.0
    @State private var number: Double = 99.0
    
    var body: some View {
        VStack {
        Text("\(Int(number))")
            .font(.system(size: 36))
            .contentTransition(.numericText())
            Button {
                         //This works when uncommented
                         //withAnimation {
                             number = .random(in: 90 ..< 100)
                         //}
                     } label: {
                         Text("Random")
                     }

    }
        //Why does this not work? 
        .onChange(of: number, initial: true) { oldNumber, newNumber in
            withAnimation {
                newNumberForAnimation = newNumber
            }
        }
     }
}

#Preview {
    ContentView()
}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img