TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

can´t change gif in background

Forums > SwiftUI

Hello dear forum, I've been reading here for some time and now I have a problem that I can't solve on my own. I want to play a gif in the background in my app. At the push of a button I want another gif to be played.

My code plays the gif very well but cannot switch to the second one.

import SwiftUI
import WebKit

struct ContentView: View {

    @State var gifList: [String] = ["GifOne","GifTwo"]
    @State var index  : Int = 0

    var body: some View {

        ZStack {
                GifImage(gifList[index])

            VStack {

            Button("Next Gif please :-)") {
                   index = index + 1 }
        } //VStack
    } //ZStack
    }
}

struct GifImage: UIViewRepresentable {
    private let name: String

    init(_ name: String) {
        self.name = name
    }

    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        let url = Bundle.main.url(forResource: name, withExtension: "gif")!
        let data = try! Data(contentsOf: url)
        webView.load(
            data,
            mimeType: "image/gif",
            characterEncodingName: "UTF-8",
            baseURL: url.deletingLastPathComponent()
        )
        webView.scrollView.isScrollEnabled = false
        return webView
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.reload()
    }

}

1      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.