SwiftUI 中的选择器适用于 ForEach 的一个版本,但不适用于另一个版本 - 错误还是预期行为? [英] Picker in SwiftUI works with one version of ForEach, but not the other - a bug, or expected behavior?
问题描述
看两个拣货员.第一个,当未注释(和第二个注释)时不起作用——当我改变房间时,Text() 不会更新.但是这里显示的代码和第二个 Picker 一样.
Behold two Pickers. The first, when uncommented (and the second commented) did not work -- when I change the room, the Text() does not get updated. But the code as shown here, with the second Picker, does.
唯一的区别在于内容闭包.为什么我创建内容的方式会影响绑定?这是错误还是预期行为?
The only difference is in the content closure. Why should how I create the content affect the binding? Is this a bug or expected behavior?
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()
}
}
}
推荐答案
Picker
选择和内容 ForEach
数据必须是相同的类型,这就是为什么第二个变体起作用 -selection 是 Int 并且 ForEach
元素是 Int,所以可能第一个变体工作应该像下面
The Picker
selection and content ForEach
data must be the same type, that's why second variant work - selection is Int and ForEach
element is Int, so to may first variant work it should be like below
使用 Xcode 12/iOS 14 测试
Tested with 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()
}
}
这篇关于SwiftUI 中的选择器适用于 ForEach 的一个版本,但不适用于另一个版本 - 错误还是预期行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!