【发布时间】:2021-05-26 18:38:26
【问题描述】:
我正在尝试为选择器分配默认值。最初,我找到了与字符串(“Tesco”)匹配的索引,但是当它起作用时,我将用传递给ProductDetail 结构的product.product_name 替换字符串。如果我删除 init() 方法(并取消注释相关变量),则错误消失并正常工作。我曾尝试将 var product = Product_ 声明移动到 init() 中,但这会导致不同的错误。我觉得我只是在尝试每一种组合,却不知道它们为什么不起作用。我确信它会在某个时候起作用,但我不知道为什么。
我收到了Argument passed to call that takes no arguments。 ProductDetail_Previews 结构中出现错误。
struct ProductDetail: View {
// Define product as a constant that takes on the values for one specific product
var product: Product_
// Define a constant for the available brands
//let all_brands = ["Asda", "Tesco", "Sainsbury's", "M&S"]
@State var all_brands: [String]
//State var currentBrand = 2
@State var currentBrand: Int
init(){
self.all_brands = ["Asda", "Tesco", "Sainsbury's", "M&S"]
// Find the first index in the list of all_brands where the string is present
self.currentBrand = all_brands.firstIndex(of: "Tesco") ?? 0
}
var body: some View {
//This is the main stack that contains everything
VStack(alignment: .leading){
//Create a form to hold the Picker(s)
Form{
Text(product.product_name)
.fontWeight(.bold)
.font(.title)
.padding()
HStack{
Text("EAN Code:")
Text(product.code).padding()
}
// Picker for Brand
Picker(selection: $currentBrand, label: Text("Brand")){
ForEach(0 ..< all_brands.count){
Text(self.all_brands[$0])
}}
}
}
}
}//Closing bracket for main VStack
struct ProductDetail_Previews: PreviewProvider {
static var previews: some View {
ProductDetail(product: products[2])
}
}
谢谢。
【问题讨论】:
-
为什么 all_brands 是 @State 属性,它看起来从未改变过?