【问题标题】:SwiftUI, can't load the image by URL with PageTabViewStyleSwiftUI,无法通过带有 PageTabViewStyle 的 URL 加载图像
【发布时间】:2021-01-25 06:32:28
【问题描述】:

您好,我正在努力解决无法在 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)
}

我想知道如何在这个 tabview 中显示图像。或者我应该构建自定义视图来制作分页视图。

【问题讨论】:

    标签: swift swiftui kingfisher


    【解决方案1】:

    我认为这是关于异步操作的。我想出了这个解决方案;

    在视图中:

    @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(命名:“defaultImage”)!”和 "width: 250, height: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
                }
            }
        }
    }
    

    不使用 Kingfisher 的另一种解决方案是;

        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))
    

    这很好用。

    【讨论】:

    • 谢谢。它运作良好。但是很遗憾,当我将它包含在 ForEach 语句中时它会出错。 +)啊,您添加了更多答案!我会检查它
    • 不客气。如果您还有问题,请随时询问。
    • 我会尝试使用 ForEach 语句从 URL 列表中制作一系列图像,但它返回错误(coordinator.collectionview : EXC_BAD_INSTRUCTION)。我想我为 ForEach(0..
    • 我通过 .id() 刷新 TabView 解决了这个问题!谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    • 2015-07-25
    • 2012-06-30
    • 1970-01-01
    相关资源
    最近更新 更多