Last active
February 6, 2025 15:32
-
-
Save mckeed/5eca743383852749add9050801d291ec to your computer and use it in GitHub Desktop.
LoadView: SwiftUI view that calls a load function and shows a `LoadingView: UIView` until the `isLoading` binding is changed to false, then displays its contents.
This file contains hidden or 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 | |
typealias IsLoadingBool = Bool // To help remember which way the bool goes (false means ready to display) | |
protocol LoadedView { | |
func load() -> Binding<IsLoadingBool> | |
} | |
// LoadingView is an existing full-screen UIView in my codebase. | |
// This could be replaced by any custom View | |
struct LoadingViewWrapper: UIViewRepresentable { | |
func makeUIView(context: Context) -> LoadingView { | |
let loadingView = LoadingView() | |
loadingView.startAnimating() | |
return loadingView | |
} | |
func updateUIView(_ loadingView: LoadingView, context: Context) { | |
} | |
} | |
struct Load<Content: View>: View { | |
@Binding var isLoading: Bool | |
let content: Content | |
init(_ loadedView: LoadedView, @ViewBuilder contentBuilder: () -> Content) { | |
_isLoading = loadedView.load() | |
content = contentBuilder() | |
} | |
init(loadFunction: () -> Binding<IsLoadingBool>, @ViewBuilder contentBuilder: () -> Content) { | |
_isLoading = loadFunction() | |
content = contentBuilder() | |
} | |
var body: some View { | |
if isLoading { | |
LoadingViewWrapper(isAnimating: $isLoading) | |
} else { | |
content | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment