我有以下选择,以选择一个事件应该重复发生的频率:
struct RecurrenceSelector: View {
@State var interval = 1
var body: some View {
NavigationView {
Form {
Section {
Picker("Every", selection: $interval) {
Text("1 week").tag(1)
ForEach(2 ..< 1000) { weeks in
Text("\(weeks) weeks")
.tag(weeks)
}
}.pickerStyle(WheelPickerStyle())
}
}
}
.onDisappear(perform: updateRruleString)
}
private func updateRruleString() {
print("INTERVAL: \(self.interval)")
}
}当我关闭视图时,如果我将Picker设置为5周,它将打印间隔: 3。如果我将其设置为20周,它将打印间隔: 18。
我不知道为什么这个价值被两个人扣除了。
(为了简洁起见,我缩短了代码,但当我注释掉所有其他代码时,它的行为也是一样的)。

发布于 2019-11-12 22:54:34
TL;DR
将ForEach(2 ..< 1000)替换为ForEach(2 ..< 1000, id: \.self)
解释
ForEach有几个初始化器。你在用
init(_ data: Range<Int>, @ViewBuilder content: @escaping (Int) -> Content)在这种情况下,选择interval对应于您选择的索引;因为范围从2开始,索引从0开始,所以选择interval总是关闭2。
如果使用带有id参数的初始化程序,
init(_ data: Data, id: KeyPath<Data.Element, ID>, content: @escaping (Data.Element) -> Content)然后,您的选择对应于元素,而不是索引。因此,您的interval属性将对应于显示的值。
https://stackoverflow.com/questions/58827647
复制相似问题