【问题标题】:swiftUI binding function valueswiftUI绑定函数值
【发布时间】:2021-10-28 17:49:30
【问题描述】:

我有这个创建图像的代码:

func getImage() -> Image {
   if coupons[index].image.isEmpty {
        return Image(systemName: "tag")
   }
   else {
        return Image(uiImage: UIImage(data: coupons[index].image) ?? UIImage())
   }
}
var body: some View {
   getImage()
}

coupons[index].image 在同一页面的另一部分更新。我希望getImage()coupons[index].image 更改时更新,因为Binding 不起作用。

编辑: coupons 是一个 State 变量,取自 UserDefaults。 index 是一个 State 变量。 coupons[index].image 使用 ImagePicker 更新。

【问题讨论】:

  • 我们需要最少的可重现的问题示例
  • 如果couponsindex 都是@State 变量,据我所知,这应该可以正常工作。我们需要更多信息和代码
  • @CloudBalancing 我不确定这在这里是否太相关,但我们仍然需要问题中的更多信息才能知道如何提供帮助

标签: swift swiftui


【解决方案1】:

根据您给定的代码,这是一种可能的方法:

struct ContentView: View {
    
    var body: some View {
        getImage(data: coupons[index].image)
    }
    
    func getImage(data: Data?) -> Image {
        
        let failureImage: Image = Image(systemName: "tag")
        
        if let safeData: Data = data {
            
            if let unwrappedUIImage: UIImage = UIImage(data: safeData) { return Image(uiImage: unwrappedUIImage) }
            else { return failureImage }
  
        }
        else { return failureImage }
        
    }
    
}

【讨论】:

    猜你喜欢
    • 2020-09-22
    • 2022-09-27
    • 1970-01-01
    • 2011-12-19
    • 2020-05-07
    • 1970-01-01
    • 2022-07-21
    • 2022-07-18
    • 2020-10-17
    相关资源
    最近更新 更多