您好,我正在努力解决无法在TabView中加载图像的问题
我想让页面视图,所以我尝试使用TabView()和PageTabViewStyle。
和我也使用KingFisher库通过URL加载图像。
当我像下面这样写代码时,这段代码不能工作。:
TabView() {
KFImage(URL(string: <ADDRESS for IMAGE>)!)
.resizable()
.clipped()
.frame(width: width_screen, height: height_banner, alignment: .topLeading)
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
我对KFImage有疑问,但如果KFImage范围不在TabView()中,它工作得很好。当我编写如下代码时,它运行良好。
var body: some View {
TabView() {
...
}
KFImage(URL(string: "<ADDRESS for IMAGE>")!)
.resizable()
.clipped()
.frame(width: width_screen, height: height_banner, alignment: .topLeading)
}
我想知道如何在这个表视图中显示图像。或者我应该构造自定义视图来创建分页视图。
我认为这是关于异步操作。我想出了这个解决方案;
在视图:
@State private var image: UIImage? = nil
在身体:
TabView() {
Image(uiImage: image ?? UIImage(named: "defaultImage")!)
.resizable()
.clipped()
.frame(width: 250, height:200, alignment: .topLeading)
.onAppear(perform: {
fetchImage()
})
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
*我使用了"UIImage(name: " defaulultimage")!"宽度:250,高度:200;但是你可以用你的代替它们。
在视图:
private func fetchImage() {
if let url = URL(string: imageUrl) {
KingfisherManager.shared.retrieveImage(with: url) { result in
let image = try? result.get().image
if let image = image {
self.image = image
}
}
}
}
另一个不使用翠鸟的解决方案是;
TabView() {
if let url = URL(string: imageUrl) {
if let imageData: NSData = NSData(contentsOf: url) {
if let image = UIImage(data: imageData as Data) {
Image(uiImage: image)
.resizable()
.clipped()
.frame(width: 250, height:200, alignment: .topLeading)
}
}
}
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
这个很好。