Skip to content

Instantly share code, notes, and snippets.

@kean kean/ImageView.swift Secret
Created Mar 18, 2020

Embed
What would you like to do?
/// - WARNING: Don't use it, this an example how _not_ to do it.
public struct ImageView: View {
@ObservedObject private var viewModel: FetchImage
private let image: (PlatformImage) -> AnyView
private let placeholder: () -> AnyView
private let error: (Error) -> AnyView
public init<ImageView: View, PlaceholderView: View, ErrorView: View>(
viewModel: FetchImage,
@ViewBuilder image: @escaping (PlatformImage) -> ImageView,
@ViewBuilder placeholder: @escaping () -> PlaceholderView,
@ViewBuilder error: @escaping (Error) -> ErrorView
) {
self.viewModel = viewModel
self.image = { AnyView(image($0)) }
self.error = { AnyView(error($0)) }
self.placeholder = { AnyView(placeholder()) }
}
public init<ImageView: View>(
viewModel: FetchImage,
@ViewBuilder image: @escaping (PlatformImage) -> ImageView
) {
self.init(
viewModel: viewModel,
image: image,
placeholder: { Rectangle().foregroundColor(.clear) },
error: { _ in Rectangle().foregroundColor(.clear) }
)
}
public init(viewModel: FetchImage) {
self.init(
viewModel: viewModel,
image: ImageView.makeImage(with:),
placeholder: { Rectangle().foregroundColor(.clear) },
error: { _ in Rectangle().foregroundColor(.clear) }
)
}
public var body: some View {
if let image = viewModel.image {
return self.image(image)
} else if let error = viewModel.error {
return AnyView(self.error(error)
.onAppear(perform: viewModel.fetch)
.onDisappear(perform: viewModel.cancel))
} else {
return AnyView(placeholder()
.onAppear(perform: viewModel.fetch)
.onDisappear(perform: viewModel.cancel))
}
}
public static func makeImage(with image: PlatformImage) -> SwiftUI.Image {
#if os(macOS)
return Image(nsImage: image)
#else
return Image(uiImage: image)
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.