Skip to content

Instantly share code, notes, and snippets.

@paulhimes
Created March 9, 2021 01:59
Show Gist options
  • Save paulhimes/57a207368e0cb26869cab6174ae0fd0b to your computer and use it in GitHub Desktop.
Save paulhimes/57a207368e0cb26869cab6174ae0fd0b to your computer and use it in GitHub Desktop.
OnLayout Tutorial 10
struct LayoutActionModifier: ViewModifier {
/// This action is run after each time the view changes.
let action: ((GeometryProxy) -> Void)?
func body(content: Content) -> some View {
content
.background(
GeometryReader { proxy in
layoutWatcher(proxy)
}
)
}
func layoutWatcher(_ proxy: GeometryProxy) -> some View {
/// This runs the action after each time the view is
/// updated.
DispatchQueue.main.async {
action?(proxy)
}
let result = Color.clear
/// This runs the action when the view first appears.
.onAppear {
action?(proxy)
}
return result
}
}
extension View {
func onLayout(
perform action: ((GeometryProxy) -> Void)? = nil
) -> some View {
self.modifier(LayoutActionModifier(action: action))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment