SwiftUI中只有一个项目时,如何替换ForEach?

8ehkhllq  于 2023-05-16  发布在  Swift
关注(0)|答案(1)|浏览(172)

我想知道是否可以替换下面的ForEach,因为我只有一个“产品”到products阵列中?

if !storeManager.products.isEmpty {
    ForEach(storeManager.products) { product in
        Button(action: {
            // Something here
        }, label: {
            Text("Purchase")
        }
    }
}
qij5mzcb

qij5mzcb1#

您可以使用if检查计数,然后根据结果显示不同的视图

let products = ["MacBook Pro"]
var body: some View {
    VStack {
        if products.count == 1 {
            button(product: products[0])
        } else {
            ForEach(products, id: \.self) { product in
                button(product: product)
            }
            .padding()
        }
    }
}

func button(product: String) -> some View {
    Button(action: {
        // Something here
    }, label: {
        Text("Purchase \(product)")
    })
}

相关问题