BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

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

}

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

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

Reply to this topic…

You need to create an account or log in to reply.

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.