lascoff
lascoff

Reputation: 1331

SwiftUI: change images on a timer with animation

I would like to change image in a view on a timer with different animation. Like slide in, fadein and out, grow from small image to fill, etc

struct ContentView: View {
    
    let images = ["1", "2", "3", "4", "5", "6", "7"] // Array of image names to showcase 
    
    @State var activeImageIndex = 0 // Index of the currently displayed image
    @State var isExpanded = false
    
    let imageSwitchTimer = Timer.publish(every: 5, on: .main, in: .common)
        .autoconnect()
    
    var body: some View {
        VStack {
            Image(images[activeImageIndex])
                .resizable()
                .aspectRatio(contentMode: .fit)
                .padding()
                .transition(.asymmetric(insertion: .scale, removal: .opacity))
                .animation(.spring())
                .onReceive(imageSwitchTimer) { _ in
                    self.activeImageIndex = (self.activeImageIndex + 1) % self.images.count
                }
        }
    }
}

Upvotes: 1

Views: 1683

Answers (1)

pawello2222
pawello2222

Reputation: 54641

You can add a computed property to specify the transition basing on activeImageIndex:

var transition: AnyTransition {
    switch activeImageIndex {
    case 0:
        return .asymmetric(insertion: .scale, removal: .opacity)
    default:
        return .identity
    }
}

and use it like this:

Image(images[activeImageIndex])
    .resizable()
    .aspectRatio(contentMode: .fit)
    .padding()
    .transition(transition) // use here
    .animation(.spring())
    .onReceive(imageSwitchTimer) { _ in
        self.activeImageIndex = (self.activeImageIndex + 1) % self.images.count
    }

Upvotes: 2

Related Questions