Skip to content

Instantly share code, notes, and snippets.

@yonat
Created February 21, 2023 05:59
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 yonat/dca57e65b38b86efc09ee24a45222957 to your computer and use it in GitHub Desktop.
Save yonat/dca57e65b38b86efc09ee24a45222957 to your computer and use it in GitHub Desktop.
SwiftUI AsyncImage that fits its image into a frame
import SwiftUI
/// AsyncImage that fits its image into a frame, shows spinner while loading, and an error if it occurs
struct ResizableAsyncImage: View {
let url: URL?
let imageContentMode: ContentMode
let maxWidth: CGFloat?
let maxHeight: CGFloat?
var body: some View {
AsyncImage(url: url) { phase in
switch phase {
case .empty:
ProgressView()
case .success(let image):
image
.resizable()
.aspectRatio(contentMode: imageContentMode)
case .failure (let error):
Image(systemName: "exclamationmark.circle")
.foregroundColor(.red)
Text(error.localizedDescription)
@unknown default:
Text("Well that was unexpected!")
}
}
.frame(maxWidth: maxWidth, maxHeight: maxHeight)
.clipped()
}
}
extension ResizableAsyncImage {
init(
url: URL?,
contentMode: ContentMode = .fit,
maxWidth: CGFloat? = nil,
maxHeight: CGFloat? = nil
) {
self.init(
url: url,
imageContentMode: contentMode,
maxWidth: maxWidth,
maxHeight: maxHeight
)
}
}
struct ResizableAsyncImage_Previews: PreviewProvider {
static var previews: some View {
ResizableAsyncImage(
url: URL(string: "https://upload.wikimedia.org/wikipedia/en/2/25/LetItBe.jpg"),
maxWidth: 200,
maxHeight: 100
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment