0

When I try to set an If query in Xcode (Swift & SwiftUI) in a view, I get the following error: Cannot invoke 'padding' with an argument list of type '(Double)'.

Once I comment out the If statement, the code works without problems. In the following code I have commented out the If statement.

What can I do to avoid the output of the error? The error is output at .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)
    }
}
1
  • 2
    Did you try .foregroundColor(product.price > 0 ? .red : .green) instead? Commented Feb 1, 2020 at 15:45

2 Answers 2

2

This problem is unrelated to SwiftUI. The problem is that an if-statement does not have a value. In your example,

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

does not evaluate to a method call that can be applied to the Text view.

Here is a simple example would not compile either:

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

The simplest solution in your case would be

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

with a conditional expression as parameter of the foreground color.

Sign up to request clarification or add additional context in comments.

Comments

0

you cannot use "normal" commands in SwiftUI - it is another concept. Normal statements you can have in functions, but not in the body. Maybe you should read some articles about the basics in SwiftUI.

Martin is right with his suggestion....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.