Skip to content

Commit

Permalink
Expose SwiftUI Image
Browse files Browse the repository at this point in the history
  • Loading branch information
leoz committed Sep 10, 2023
1 parent 37135b4 commit 0d99529
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 14 deletions.
5 changes: 4 additions & 1 deletion Demo/CachedImageDemo/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@ struct ContentView: View {
CachedImage(
url: url,
placeholder: { Text("Loading ...") },
image: { Image(platformImage: $0).resizable() }
content: { image in
image.resizable()
.aspectRatio(contentMode: .fit)
}
)
.frame(idealHeight: geometry.size.width / 2 * 3) // 2:3 aspect ratio
}
Expand Down
25 changes: 12 additions & 13 deletions Sources/CachedImage/CachedImage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,38 +8,37 @@

import SwiftUI

public struct CachedImage<Placeholder: View>: View {
public struct CachedImage<Placeholder: View, Content: View>: View {
@StateObject private var loader: ImageLoader
private let placeholder: Placeholder
private let image: (PlatformImage) -> Image
private let content: (Image) -> Content
private let url: URL

public init(
url: URL,
@ViewBuilder placeholder: () -> Placeholder,
@ViewBuilder image: @escaping (PlatformImage) -> Image = Image.init(platformImage:)
placeholder: @escaping () -> Placeholder,
content: @escaping (Image) -> Content
) {
self.placeholder = placeholder()
self.image = image
self.content = content
self.url = url
_loader = StateObject(wrappedValue: ImageLoader(url: url, cache: Environment(\.imageCache).wrappedValue))
}

public var body: some View {
content
contentOrImage
.onAppear(perform: loader.load)
.onChange(of: url) { newUrl in
loader.reload(url: newUrl)
}
}

private var content: some View {
Group {
if loader.image != nil {
image(loader.image!)
} else {
placeholder
}
@ViewBuilder
private var contentOrImage: some View {
if let platformImage = loader.image {
content(Image(platformImage: platformImage))
} else {
placeholder
}
}
}

0 comments on commit 0d99529

Please sign in to comment.