Files
suixinkan_ios_new/suixinkan/Core/UI/RemoteImage.swift

82 lines
2.4 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// RemoteImage.swift
// suixinkan
//
// Created by Codex on 2026/6/22.
//
import Kingfisher
import SwiftUI
/// 使 Kingfisher
struct RemoteImage<Placeholder: View>: View {
let urlString: String?
let contentMode: SwiftUI.ContentMode
@ViewBuilder let placeholder: () -> Placeholder
@State private var didFail = false
///
init(
urlString: String?,
contentMode: SwiftUI.ContentMode = .fill,
@ViewBuilder placeholder: @escaping () -> Placeholder
) {
self.urlString = urlString
self.contentMode = contentMode
self.placeholder = placeholder
}
var body: some View {
Group {
if let url = imageURL, !didFail {
KFImage(url)
.placeholder { placeholder() }
.onFailure { _ in didFail = true }
.resizable()
.cacheOriginalImage()
.aspectRatio(contentMode: contentMode)
} else {
placeholder()
}
}
.onChange(of: normalizedURLString) { _, _ in
didFail = false
}
}
private var imageURL: URL? {
guard let normalizedURLString else { return nil }
return URL(string: normalizedURLString)
}
private var normalizedURLString: String? {
let text = urlString?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
return text.isEmpty ? nil : text
}
}
/// Kingfisher
struct RemoteAvatarImage: View {
let urlString: String
let systemImageName: String
let iconSize: CGFloat
///
init(urlString: String, systemImageName: String = "person.fill", iconSize: CGFloat = 44) {
self.urlString = urlString
self.systemImageName = systemImageName
self.iconSize = iconSize
}
var body: some View {
RemoteImage(urlString: urlString, contentMode: .fill) {
Image(systemName: systemImageName)
.font(.system(size: iconSize, weight: .semibold))
.foregroundStyle(AppDesign.primary)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(AppDesign.primarySoft)
}
}
}