首页 > 解决方案 > 使用 IF 查询在 Xcode 中返回错误

问题描述

当我尝试在视图中的 Xcode(Swift 和 SwiftUI)中设置 If 查询时,我收到以下错误:无法使用类型为“(双)”的参数列表调用“填充”。

一旦我注释掉 If 语句,代码就可以正常工作。在下面的代码中,我注释掉了 If 语句。

我该怎么做才能避免错误的输出?错误在 .padding(0.0) 处输出

    var body: some View {
    NavigationLink(destination: TransactionDetail(product: product)) {
        HStack {

            Text("X")
                .font(.largeTitle)
                .clipShape(Circle())
                .foregroundColor(.green)
                .overlay(Circle().stroke(Color.green, lineWidth: 1))
                .shadow(radius: 5)

            VStack(alignment: .leading) {
                HStack {
                   Text(product.name)
                        .font(.headline)
                        .foregroundColor(.black)
                }
                Text("21. Januar")
                    .font(.caption)
                    .foregroundColor(.black)
            }
            Spacer()
            Text("\(product.price),00 €")
                .font(.caption)
                .padding(2)
                /*
                if product.price > 0 {
                    .foregroundColor(.black)
                } else {
                    .foregroundColor(.black)
                }
                */
                .cornerRadius(5)
        }
        .padding(0.0)
    }
}

标签: iosswiftxcodeswiftui

解决方案


这个问题与 SwiftUI 无关。问题是 if 语句没有值。在你的例子中,

if product.price > 0 {
    .foregroundColor(.black)
} else {
    .foregroundColor(.black)
}

不会评估可应用于Text视图的方法调用。

这是一个也不会编译的简单示例:

var uc = true
let string = "Hello World"
            if uc {
                .uppercased()
            } else {
                .lowercased()
            }

在您的情况下,最简单的解决方案是

Text("\(product.price),00 €")
    .font(.caption)
    .padding(2)
    .foregroundColor(product.price > 0 ? .red : .green)
    .cornerRadius(5)

使用条件表达式作为前景色的参数。


推荐阅读