gpt4 book ai didi

ios - SwiftUI : Picker does not update correctly when changing datasource

转载 作者:行者123 更新时间:2023-12-02 10:36:14 27 4
gpt4 key购买 nike

我刚刚开始学习 SwiftUI,却陷入了困境!

我试图在更改另一个段的值时更改段样式选择器数据源。但不知怎的,它没有按预期工作!否则我可能编码错误。请问谁能解答一下吗?

这是我的代码:

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!

默认选择第一个片段: enter image description here

更改分割:

enter image description here

将分段更改回第一个分段:

enter image description here

任何帮助或建议将不胜感激。

最佳答案

Nick Polychronakis 在这个分支中解决了这个问题: https://github.com/nickpolychronakis/100DaysOfSwiftUI/tree/master/UnitCoverter

解决方案是将 .id(:identifier:) 添加到您的选择器中,使其具有唯一性。

可观察变量:

@State var unit = 0

主选择器:

Picker("Length", selection: $unit) {
ForEach(0 ..< inputUnitTypes.count) {
Text("\(self.inputUnitTypes[$0].description)")
}
}
.pickerStyle(SegmentedPickerStyle())

二级选择器之一,其内容由单位变量确定。

Picker("Length", selection: $inputUnit) {
ForEach(0 ..< selected.count) {
Text("\(self.selected[$0].description)")
}
}
.id(unit)

关于ios - SwiftUI : Picker does not update correctly when changing datasource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58352798/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com