Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save christianselig/7b56623a09916faf47cd26eabc67dbb0 to your computer and use it in GitHub Desktop.
Save christianselig/7b56623a09916faf47cd26eabc67dbb0 to your computer and use it in GitHub Desktop.
//
// ContentView.swift
// UnderstandSwiftUIChange
//
// Created by Christian Selig on 2024-04-04.
//
import SwiftUI
import WebKit
import UIKit
struct ContentView: View {
@State var viewModel: ViewModel = .init(url: URL(string: "https://apple.com")!)
var body: some View {
VStack {
Text("Welcome to my cool View")
WebPlayerView(viewModel: viewModel)
}
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5)) {
viewModel = .init(url: URL(string: "https://christianselig.com")!)
}
}
.onChange(of: viewModel) { oldValue, newValue in
// IS called after change 🥳
print("Changed to \(newValue.url) from \(oldValue.url)")
}
}
}
struct WebPlayerView: View {
@State var viewModel: ViewModel
var body: some View {
ZStack {
WebView(viewModel: viewModel)
}
.onChange(of: viewModel) { oldValue, newValue in
// Not called after change 😥
print("Our WebPlayerView changed from \(oldValue.url) to \(newValue.url)")
}
}
}
struct WebView: UIViewRepresentable {
@State var viewModel: ViewModel
func makeUIView(context: Context) -> some UIView {
let webView = WKWebView()
webView.load(URLRequest(url: viewModel.url))
return webView
}
func updateUIView(_ uiView: UIViewType, context: Context) {
// Not called after change 😥
print("Update called on UIViewRepresentable, our URL is now \(viewModel.url)")
}
}
@Observable
class ViewModel: NSObject {
let url: URL
init(url: URL) {
self.url = url
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment