SwiftUI:使用动画更改计时器上的图像

时间:2020-11-02 23:20:31

标签: swiftui

我想使用其他动画在计时器的视图中更改图像。像滑入,淡入和淡出,从小图像成长为填充等

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
                }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以添加一个计算属性来基于activeImageIndex指定过渡:

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

并像这样使用它:

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
    }