Is it possible to change image with fade animation using same Image? (SwiftUI)

后端 未结 1 1001
半阙折子戏
半阙折子戏 2021-01-21 20:39

According to my logic, on tap gesture to the image it should be changed with fade animation, but actual result is that image changes without animation. Tested with Xcode 11.3.1,

相关标签:
1条回答
  • 2021-01-21 21:24

    Here is possible approach using one Image (for demo some small modifications made to use default images). The important changes marked with comments.

    demo

    enum ImageEnum: String {
        case img1 = "1.circle"
        case img2 = "2.circle"
        case img3 = "3.circle"
    
        func next() -> ImageEnum {
            switch self {
                case .img1: return .img2
                case .img2: return .img3
                case .img3: return .img1
            }
        }
    }
    struct QuickTest: View {
        @State private var img = ImageEnum.img1
        @State private var fadeOut = false
        var body: some View {
            Image(systemName: img.rawValue).resizable().frame(width: 300, height: 300)
                .opacity(fadeOut ? 0 : 1)
                .animation(.easeInOut(duration: 0.25))    // animatable fade in/out
                .onTapGesture {
                    self.fadeOut.toggle()                 // 1) fade out
    
                    // delayed appear
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
                        withAnimation {
                            self.img = self.img.next()    // 2) change image
                            self.fadeOut.toggle()         // 3) fade in
                        }
                    }
                }
        }
    }
    
    0 讨论(0)
提交回复
热议问题