Created
May 3, 2023 20:45
-
-
Save pmark/3ab1907116eabe704a3ab5ce3d730eb8 to your computer and use it in GitHub Desktop.
SwiftUI .onRender view modifier
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
/* | |
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