我对Swift和编码都很陌生,所以如果这是一个非常简单的问题,我很抱歉。
我正在尝试在选取器的两侧添加一个按钮,以允许用户在选取器中向上/向下移动选择(我的选取器是从数组中填充的(-我正在应用程序的另一部分中使用此选择。
下面的代码可以工作,但只更新示例Text,但不会更新pickert中的选择:以正确更新。
你知道我做错了什么吗?
import SwiftUI
struct ContentView: View {
let myArray = ["Period 1", "Period 2", "Period 3", "Period 4", "Period 5", "Period 6", "Period 7", "Period 8", "Period 9", "Period 10", "Period 11", "Period 12", "Period 13"]
@State var currentIndex = 0
var body: some View {
VStack(spacing: 20) {
HStack {
Button(action: {
if currentIndex == 0 {
} else {
currentIndex -= 1
}
}) {
Image(systemName: "chevron.left.circle")
.imageScale(.large)
}
.padding(2)
.frame(maxWidth: .infinity, alignment: .leading)
Picker(selection: $currentIndex, label: Text("Picker")) {
ForEach(myArray, id: .self) {
Text($0)
}
}
Button(action: {
if currentIndex == 12 {
} else {
currentIndex += 1
}
}) {
Image(systemName: "chevron.right.circle")
.imageScale(.large)
}
.padding(2)
.frame(maxWidth: .infinity, alignment: .trailing)
}
.padding()
Text("(myArray[currentIndex])")
}
}
}
''
这里的问题是,您正在以编程方式更新State变量currentIndex
,但没有修改数组选择。为了实现这一点,您需要在索引而不是元素上迭代数组,因此将Picker
代码更改为该
Picker(selection: $currentIndex, label: Text("Picker")) {
ForEach(myArray.indices) { index in
Text(myArray[index])
}
}
在这里,选择器中的每个项目都自动获得index
的原始值的id
,该值与currentIndex
相匹配,这使得该项工作正常。
要直接使用数组的元素,这里有一个替代解决方案,其中添加了一个新的State变量来保存选定的字符串。
@State var currentSelection = ""
@State var currentIndex = 0 {
didSet {
currentSelection = myArray[currentIndex]
}
}
选择器代码更改为
Picker(selection: $currentSelection, label: Text("Picker")) {
ForEach(myArray, id: .self) { period in
Text(period)
}
}
但是代码的其余部分是相同的,因为按钮仍然使用currentIndex