Once the button has been tapped I want to refresh the currently displayed GIF with the next GIF in the array. I am using SDWebImageSwiftUI to display the GIF. The following error message is shown when I try to change the array value:
Cannot invoke 'init' with an argument list of type '(url: URL?, options: 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
}
}
}
}
I thought using @Published
would refresh the view with the new GIF once the value has been changed on currentIndex
As I know when trying sample in HERE, in body of SwiftUI, we can just render UI, cannot write logic code like self.currentIndex += 1
. So when you write logic code here, this will appear some weird error. Just put this code into Button action. I tried your code, edit somewhere and it worked.
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)
}
}
}