如何使用数组中的下一个GIF刷新视图

时间:2019-11-28 21:06:05

标签: swiftui sdwebimage

点击按钮后,我想用数组中的下一个GIF刷新当前显示的GIF。我正在使用SDWebImageSwiftUI来显示GIF。当我尝试更改数组值时,显示以下错误消息:

  

无法使用类型为'(url:URL ?,   选项:SDWebImageOptions)'

import SwiftUI
import SDWebImage
import SDWebImageSwiftUI

struct TrainingView : View {
    @State private var forwardButtonTapped = false
    @Published var currentIndex = 0
    var GIFS = ["https://media3.giphy.com/media/xULW8v7LtZrgcaGvC0/giphy.gif?cid=790b7611cabeafc835b67239aa3fa3f3abc3df4322c3e4ea&rid=giphy.gif", "https://media1.giphy.com/media/6tHy8UAbv3zgs/giphy.gif?cid=790b7611cabeafc835b67239aa3fa3f3abc3df4322c3e4ea&rid=giphy.gif"]

    var body: some View {
            VStack(){

            AnimatedImage(url: URL(string: GIFS[currentIndex]), options: [.progressiveLoad])
                .scaledToFit()

            Button(action:{
                self.forwardButtonTapped.toggle()
            }) {Image("forwardButton")}

            if forwardButtonTapped {
                self.currentIndex += 1
            }
        }
    }
}

我认为使用@Published会在currentIndex上更改值后用新的GIF刷新视图

1 个答案:

答案 0 :(得分:1)

据我所知,在HERE中尝试采样时,在SwiftUI主体中,我们只能呈现UI,而不能编写类似self.currentIndex += 1的逻辑代码。因此,当您在此处编写逻辑代码时,这会出现一些奇怪的错误。只需将这段代码放入Button操作即可。我尝试了您的代码,在某个地方进行了编辑,并且成功了。

struct TrainingView : View {
    @State private var forwardButtonTapped = false
    @State var currentIndex = 0
    var GIFS = ["https://media3.giphy.com/media/xULW8v7LtZrgcaGvC0/giphy.gif?cid=790b7611cabeafc835b67239aa3fa3f3abc3df4322c3e4ea&rid=giphy.gif", "https://media1.giphy.com/media/6tHy8UAbv3zgs/giphy.gif?cid=790b7611cabeafc835b67239aa3fa3f3abc3df4322c3e4ea&rid=giphy.gif"]

    var body: some View {
            VStack(){

            AnimatedImage(url: URL(string: GIFS[currentIndex]), options: [.progressiveLoad])
                .scaledToFit()

            Button(action:{
                self.currentIndex += 1
            }) {Text("CLICK @@@@@")}.frame(width: 150, height: 50, alignment: .leading)
        }
    }
}