【问题标题】:Swiftui seems not to work correctly with Cocoapods and FirebaseSwiftui 似乎无法与 Cocoapods 和 Firebase 一起正常工作
【发布时间】:2019-10-29 18:33:29
【问题描述】:

我正在尝试使用 SwiftUI 创建一个 iOS 应用程序。我的数据存储在 Google Firebase 实时数据库中。我将数据提取到 ObservableObject 中,以便在添加或删除数据时动态加载 UI。 但由于某种原因,对于 Text(),我总是收到错误“表达式类型不明确,没有更多上下文”。

我已经尝试删除 if 语句和 Text() 但是我在其他地方遇到了错误。例如。我也得写

HStack{ ... }.padding(.leading, CGFloat(20))

如果我不将 20 转换为 CGFloat,我会收到错误消息“'CGFloat' is not convertible to 'CGFloat?'”。 我知道 SwiftUI 的错误消息还不是很好,因为几乎 90% 的代码失败都会导致一些模棱两可的 bla 错误。但是这里我真的不知道这些错误是从哪里来的。

import SwiftUI

struct IngredientsTab: View {

    @ObservedObject var ingredientsVM: IngredientViewModel = IngredientViewModel()

    var body: some View {

        NavigationView {
            List {
                ForEach(ingredientsVM.ingredients, id: \.self){ (ingredient) in
                    NavigationLink(destination: IngredientDetailView(ingredient: ingredient)){
                        VStack {
                            HStack {
                                Text(ingredient.name)
                                Spacer()

                                if (Type.NONALC == ingredient.type) {
                                    self.modifier(LabelViewModifier(label: "Non-alcoholic", backgroundColor: .green))
                                } else {
                                    self.modifier(LabelViewModifier(label: "Alcoholic", backgroundColor: .red))
                                }
                            }

                            if (ingredient.pieceGood) {

                                HStack {
                                    Image(systemName: "checkmark.circle.fill")
                                        .foregroundColor(Color.green)
                                    Text("Piece good") // Here I'm getting the error
                                    Spacer()
                                }
                                .padding(.leading, 20)
                            }
                        }
                    }
                }
            }
        }
    }
}

所以它似乎在某种程度上与 SwiftUI 相关(因为它显然还不能完美运行),但也与 Cocoapods/Firebase 相关。在另一个项目中,我有类似的方法,但没有使用任何 Pod,它运行良好。

【问题讨论】:

  • 这与 Cocoapods 和/或 FireBase 无关。基于此链接:stackoverflow.com/questions/56683764/…,看来您需要使您的成分模型符合Identifiable 协议。
  • 如果没有看到您的 IngredientViewModel 和 LabelViewModifier,很难说问题出在哪里。

标签: ios swift firebase-realtime-database cocoapods swiftui


【解决方案1】:

我终于找到了问题所在。 我的成分继承自 Identifiable 也继承自 NSObject。结合一些错误的构造函数和写法

id: \.self

在 ForEach 循环中导致了这种奇怪的行为。我将我的成分更新为正确的模型,并从 ForEach 循环中删除了上述行,然后它就起作用了。

感谢您的帮助!

PS:它既不与任何 Pod 相关,也不与 Firebase 相关;)

【讨论】:

  • 对于未来的读者,也许您可​​以编辑您的标题、问题和标签以删除提及 CocoaPads 和 FireBase。
猜你喜欢
  • 1970-01-01
  • 2019-05-12
  • 1970-01-01
  • 1970-01-01
  • 2017-09-04
  • 2012-05-06
  • 2013-02-17
  • 2017-10-09
  • 2017-08-03
相关资源
最近更新 更多