看两个采摘者。第一个没有注释(第二个注释)时不起作用-当我改变房间时,Text()不会更新。但是这里显示的代码和第二个Picker一样。
唯一的区别是内容关闭。为什么我如何创建内容会影响绑定?这是错误还是预期的行为?
struct ContentView: View {
var rooms = ["Kitchen", "Dining Room", "Living Room", "Bathroom"]
@State private var selectedRoomIndex = 0
var body: some View {
VStack {
/* Doesn't work :-(
Picker(selection: $selectedRoomIndex, label: Text("Room: ")) {
ForEach(rooms, id: \.self){ room in
Text(room)
}
}
*/
/* This works, huzzah! But why? */
Picker(selection: $selectedRoomIndex, label: Text("Room: ")) {
ForEach(0 ..< rooms.count){
Text(rooms[$0])
}
}
Text("Chosen room: \(rooms[selectedRoomIndex])")
Spacer()
}
}
}
答案 0 :(得分:0)
Picker
选择项和内容ForEach
数据必须是同一类型,这就是第二种变体工作的原因-选择是Int而ForEach
元素是Int,因此第一种变体可以工作应该像下面的
通过Xcode 12 / iOS 14测试
@State private var selectedRoom: String = "Kitchen"
var body: some View {
VStack {
Picker(selection: $selectedRoom, label: Text("Room: ")) {
ForEach(rooms, id: \.self){ room in
Text(room)
}
}
Text("Chosen room: \(selectedRoom)")
Spacer()
}
}