Home > Back-end >  Swiftui Button to display an array of images one after another
Swiftui Button to display an array of images one after another

Time:10-29

I am trying to create an animation of images in Swiftui. I want to click a button with a label as an image (this image is the first element in the array of images). After the button is clicked, I then want to display the rest of the images in the array and have the label image change every second with each new element of the array. Any help with this would be great.

Currently I can use a button click to change the image after each click, but I want an animation of the images after one click

What I have:

   Button {
       activeImageIndex  = 1
   } label: {
      Image(images[activeImageIndex])
   }

CodePudding user response:

We can simply use Combine's delay() operator.

import SwiftUI
import Combine

struct ContentView: View {
    let images = [ "square.and.arrow.up", "pencil.circle.fill", "moon.stars.fill"]
    @State private var activeImageIndex = 0
    @State private var cancellable: AnyCancellable? = nil
    
    var body: some View {
        Button {
            cancellable = [0,1,2].publisher
                .flatMap(maxPublishers: .max(1)) { Just($0).delay(for: 3, scheduler: RunLoop.main) } //<- delay for: 3 sec
                .sink { value in
                    activeImageIndex = value
                }
            
        } label: {
            Image(systemName: images[activeImageIndex])
                .animation(.easeIn, value: activeImageIndex)
        }
    }
}
  • Related