Skip to content

Instantly share code, notes, and snippets.

@mckeed
Created August 12, 2022 20:02
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 mckeed/5eca743383852749add9050801d291ec to your computer and use it in GitHub Desktop.
Save mckeed/5eca743383852749add9050801d291ec to your computer and use it in GitHub Desktop.
SwiftUI view that calls a load function and shows a `LoadingView: UIView` until the `isLoading` binding is changed to false, then displays its contents.
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