在 iOS 中加载网络图片,常见的方法是使用 UIImageView
类的 sd_setImage(with: URL)
方法。具体使用方法如下:
首先,创建一个 UIImageView
对象,并将它的 frame
设置为所需的大小:
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
然后,设置图像的 URL:
let imageURL = URL(string: "https://example.com/image.png")
最后,使用 sd_setImage(with: URL)
方法将图像加载到 imageView
中:
imageView.sd_setImage(with: imageURL)
这种方法会自动缓存图像,以便在稍后使用时能够快速加载。
注意:在使用 sd_setImage(with: URL)
方法时,需要导入 SDWebImage
库。如果您想使用其他方法加载图像,可以使用 URLSession
或 NSURLSession
类来完成。