Created
February 21, 2023 05:59
-
-
Save yonat/dca57e65b38b86efc09ee24a45222957 to your computer and use it in GitHub Desktop.
SwiftUI AsyncImage that fits its image into a frame
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 | |
/// 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