首页 > 其他分享 >04:SwiftUI-网络图片

04:SwiftUI-网络图片

时间:2023-03-19 19:01:10浏览次数:35  
标签:04 downloadWebImage print let baseImage var SwiftUI data 图片

 

 

正文

 

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

 

标签:04,downloadWebImage,print,let,baseImage,var,SwiftUI,data,图片
From: https://www.cnblogs.com/zyzmlc/p/17233937.html

相关文章