Created
April 5, 2024 14:23
-
-
Save christianselig/7b56623a09916faf47cd26eabc67dbb0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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