Home > AI > IOS > SwiftUI >

AnimatingImageView

how to play GIF in SwiftUI?

struct ContentView: View {
    private let images = ["speaker.wave.1",
                          "speaker.wave.2",
                          "speaker.wave.3"]
        .map { Image(systemName: $0) }
    
    var body: some View {
        AnimatingImageView(images: images)
    }
}


struct AnimatingImageView: View {
    let images: [Image]

    @ObservedObject private var model = AnimatingImageViewModel(interval: 0.5)
        
    var body: some View {
        images[model.imgIdx % images.count]
    }
}


private class AnimatingImageViewModel: ObservableObject {
    private var timer: Timer?

    @Published var imgIdx: Int = 0
    
    init(interval: Double) {
        timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { _ in self.imgIdx += 1 }
    }
}

Leave a Reply