Last active
February 1, 2024 17:50
-
-
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.
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
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