SwiftUI:更改数据源时Picker无法正确更新 [英] SwiftUI : Picker does not update correctly when changing datasource
问题描述
我刚刚开始学习SwiftUI并被卡在某个地方!
I have just started learning SwiftUI and got stuck somewhere!
我试图在更改另一个细分的值时更改细分样式的选择器数据源.但是不知何故,它无法正常工作!否则我可能编码有误.有人可以找出答案吗?
I am trying to change segment styled picker datasource when changing value of another segment. But somehow it is not working as expected! Or else I might have coded something wrong. Can anyone figure it out please?
这是我的代码:
import SwiftUI
struct ContentView: View {
@State var selectedType = 0
@State var inputUnit = 0
@State var outputUnit = 1
let arrTypes = ["Temperature", "Length"]
var arrData: [String] {
switch self.selectedType {
case 0:
return ["Celsius", "Fahrenheit", "Kelvin"] //Temperature
case 1:
return ["meters", "kilometers", "feet", "yards", "miles"] //Length
default:
return ["Celsius", "Fahrenheit", "Kelvin"]
}
}
var body: some View {
NavigationView{
Form
{
Section(header: Text("Choose type"))
{
Picker("Convert", selection: $selectedType) {
ForEach(0 ..< 2, id: \.self)
{ i in
Text(self.arrTypes[i])
}
}
.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("From"))
{
Picker("", selection: $inputUnit) {
ForEach(0 ..< arrData.count, id: \.self)
{
Text(self.arrData[$0])
}
}
.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("To"))
{
Picker("", selection: $outputUnit) {
ForEach(0 ..< arrData.count, id: \.self)
{
Text(self.arrData[$0])
}
}
.pickerStyle(SegmentedPickerStyle())
}
}
}
}
}
当我将段从Length
更改回Temperature
时,它将以某种方式合并数组.我尝试调试并打印日志中的arrData
计数,然后它显示正确的结果,但未更新UI!
When I change segment from Length
back to Temperature
it merges the array somehow. I tried to debug and print the arrData
count in log, then it prints correct result but not updating the UI!
默认情况下选择的第一个细分:
更改细分:
将细分重新更改为第一个
任何帮助或建议,将不胜感激.
Any help or suggestion would greatly be appreciated.
推荐答案
Nick Polychronakis在此fork中解决了它: https://github.com/nickpolychronakis/100DaysOfSwiftUI/tree/master/UnitCoverter
Nick Polychronakis solved it in this fork: https://github.com/nickpolychronakis/100DaysOfSwiftUI/tree/master/UnitCoverter
解决方案是将.id(:identifier :)添加到选择器中,使其唯一.
The solution is to add .id(:identifier:) to your picker so it is unique.
可观察的变量:
@State var unit = 0
主选择器:
Picker("Length", selection: $unit) {
ForEach(0 ..< inputUnitTypes.count) {
Text("\(self.inputUnitTypes[$0].description)")
}
}
.pickerStyle(SegmentedPickerStyle())
辅助选择器之一,其内容由unit变量确定.
One of secondary pickers which content is determined by the unit variable.
Picker("Length", selection: $inputUnit) {
ForEach(0 ..< selected.count) {
Text("\(self.selected[$0].description)")
}
}
.id(unit)
这篇关于SwiftUI:更改数据源时Picker无法正确更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!