Skip to content

Instantly share code, notes, and snippets.

@pmark
Created May 3, 2023 20:45
Show Gist options
  • Save pmark/3ab1907116eabe704a3ab5ce3d730eb8 to your computer and use it in GitHub Desktop.
Save pmark/3ab1907116eabe704a3ab5ce3d730eb8 to your computer and use it in GitHub Desktop.
SwiftUI .onRender view modifier
/*
USAGE
struct ContentView: View {
var body: some View {
Text("Hello, World!")
.onRender {
print("View rendered or updated")
}
}
}
*/
import SwiftUI
import Combine
class RenderNotifier: ObservableObject {
let objectWillChange = PassthroughSubject<Void, Never>()
func viewRendered() {
objectWillChange.send()
}
}
struct ViewRenderedNotifier: ViewModifier {
@StateObject private var renderNotifier = RenderNotifier()
let onRender: () -> Void
func body(content: Content) -> some View {
content
.onReceive(renderNotifier.objectWillChange) {
onRender()
}
.onAppear {
renderNotifier.viewRendered()
}
}
}
extension View {
func onRender(_ onRender: @escaping () -> Void) -> some View {
self.modifier(ViewRenderedNotifier(onRender: onRender))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment