04:SwiftUI-网络图片
正文
import SwiftUI struct WebImagePage: View { @State private var baseImage: UIImage? = nil let placeHolderImage = UIImage(named: "icon")! var body: some View { Image(uiImage: self.baseImage ?? placeHolderImage) .resizable() .frame(width: 150, height: 150, alignment: .center) .onTapGesture { downloadWebImage() print("更换图片") } .onAppear(perform: downloadWebImage) } private func downloadWebImage() { guard let url = URL(string: "https://picsum.photos/300/300?i=88") else { print("无效的图片") return } URLSession.shared.dataTask(with: url) { (data, response, error) in if let data = data, let image = UIImage(data: data) { self.baseImage = image } else { print("error:\(String(describing: error))") } }.resume() } } #if DEBUG struct WebImagePage_Previews : PreviewProvider { static var previews: some View { WebImagePage() } } #endif