Skip to content

Instantly share code, notes, and snippets.

@levochkaa
Created February 19, 2023 17:02
Show Gist options
  • Save levochkaa/c573c66367e4ea5b566b009a9f0ac79d to your computer and use it in GitHub Desktop.
Save levochkaa/c573c66367e4ea5b566b009a9f0ac79d to your computer and use it in GitHub Desktop.
To check, when the view is visible
struct VisibleKey: PreferenceKey {
static var defaultValue: Bool = false
static func reduce(value: inout Bool, nextValue: () -> Bool) { }
}
private struct OnVisible: ViewModifier {
@State var action: (() -> Void)?
func body(content: Content) -> some View {
content
.overlay {
GeometryReader { proxy in
Color.clear
.preference(
key: VisibleKey.self,
value: UIScreen.main.bounds.intersects(proxy.frame(in: .global))
)
.onPreferenceChange(VisibleKey.self) { isVisible in
guard isVisible else { return }
action?()
}
}
}
}
}
extension View {
func onVisible(_ action: @escaping () -> Void) -> some View {
modifier(OnVisible(action: action))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment