Created
March 9, 2021 01:59
-
-
Save paulhimes/57a207368e0cb26869cab6174ae0fd0b to your computer and use it in GitHub Desktop.
OnLayout Tutorial 10
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
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