SwiftUI:更改数据源时,选择器无法正确更新

iRi*_*iya 5 picker ios swift ios13 swiftui

我刚刚开始学习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())
            }                

        }
    }
}
}
Run Code Online (Sandbox Code Playgroud)

当我将段从Length原来更改回Temperature它以某种方式合并数组时。我尝试调试并打印arrData日志中的计数,然后它打印正确的结果,但未更新UI!

默认情况下选择的第一段: 在此处输入图片说明

变更区隔:

在此处输入图片说明

将细分更改回第一:

在此处输入图片说明

Any help or suggestion would greatly be appreciated.

emi*_*min 11

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

解决方案是将 .id(:identifier:) 添加到您的选择器中,使其独一无二。

可观察变量:

@State var unit = 0
Run Code Online (Sandbox Code Playgroud)

主要选择器:

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

内容由单元变量确定的辅助选择器之一。

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

  • 我明白了,tnx分享!关于 SwiftUI 的一件非常棘手的事情是,你永远无法确定它是否是一个错误,或者它应该像那样工作 XD (2认同)