Skip to content

Instantly share code, notes, and snippets.

@dayanruben
Last active February 1, 2024 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dayanruben/03dc746e539a15666ab34f16bd282d41 to your computer and use it in GitHub Desktop.
Save dayanruben/03dc746e539a15666ab34f16bd282d41 to your computer and use it in GitHub Desktop.
This Swift code is a SwiftUI extension for the View protocol. It adds a new method `onChangeVisibility(perform:)` that allows you to perform an action when the visibility of the view changes.
import SwiftUI
extension View {
func onChangeVisibility(perform action: @escaping (Bool) -> Void) -> some View {
modifier(BecomingVisible(action: action))
}
}
private struct BecomingVisible: ViewModifier {
@State var action: ((Bool) -> 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
action(isVisible)
}
}
}
}
struct VisibleKey: PreferenceKey {
static var defaultValue: Bool = false
static func reduce(value: inout Bool, nextValue: () -> Bool) { }
}
}
// Simple sample
struct ContentView: View {
var body: some View {
Text("Hi there!")
.font(.largeTitle)
.padding()
.onChangeVisibility { isVisible in
print("Text is now \(isVisible ? "visible" : "hidden")")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment