@State var 没有改变 - SwiftUI 选择器

@State var not changing - SwiftUI picker

我是swift的真正新手,但我被这个问题困住了...... 我正在构建一个选择器来更改光学处方,但我无法更改 SPH 和 CYL 值(双倍),而 AX 效果很好。有什么帮助吗? 还有文本的显示方式,我试图添加 .format 修饰符只是为了显示 2 位小数,但仍然没有运气。 谢谢!

import SwiftUI

struct ContentView: View {

@State var selectedsph = 0.0
@State var selectedcyl = 0.0
@State var selectedax = 0

var sph : [Double] = Array(stride(from: -20.00, through: 20.00, by: 0.25))
var cyl : [Double] = Array(stride(from: -10.00, through: 10.00, by: 0.25))
var ax = [Int](0...180)


var body: some View {
    GeometryReader { geometry in
        VStack {
            Spacer()
            HStack(spacing:0) {
                
                Picker(selection: self.$selectedsph, label: Text("")) {
                    ForEach(0 ..< self.sph.count) { index in
                        Text("Sph  " + "\(self.sph[index])").tag(index)
                    }
                }
                .pickerStyle(.wheel)
                .frame(width: geometry.size.width/3, height: 150)
                .compositingGroup()
                .clipped()
                
                Picker(selection: self.$selectedcyl, label: Text("Picker")) {
                    ForEach(0 ..< self.cyl.count) { index in
                        Text("Cyl  " + "\(self.cyl[index])").tag(index)
                    }
                }
                .pickerStyle(.wheel)
                .frame(width: geometry.size.width/3.5, height: 150)
                .compositingGroup()
                .clipped()
                
                Picker(selection: self.$selectedax, label: Text("Picker")) {
                    ForEach(0 ..< self.ax.count) { index in
                        Text("AX  " + "\(self.ax[index])").tag(index)
                    }
                }
                .pickerStyle(.wheel)
                .frame(width: geometry.size.width/3, height: 150)
                .compositingGroup()
                .clipped()
                
            }.padding()
        }
        HStack(alignment: .center) {
            Text("Occhio Destro: SF: \(selectedsph)  Cyl: \(selectedcyl)  Ax: \(selectedax)")
                .fontWeight(.medium).multilineTextAlignment(.center).padding(.all)
            
        }
        Spacer()
        
    }
  }
}

选择器值是所选值的索引。将您的 @State 变量更改为保持 Int:

@State var selectedsph = 0
@State var selectedcyl = 0
@State var selectedax = 0

并更改您的 Text 以使用索引来查找值。添加 specifier: "%.2f" 以仅显示 2 位小数:

Text("Occhio Destro: SF: \(sph[selectedsph], specifier: "%.2f")  Cyl: \(cyl[selectedcyl], specifier: "%.2f")  Ax: \(ax[selectedax])")
            .fontWeight(.medium).multilineTextAlignment(.center).padding(.all)