【问题标题】:Converting from text field string to double从文本字段字符串转换为双精度
【发布时间】:2022-01-03 10:13:00
【问题描述】:

我目前正在开发一个体重跟踪应用程序,作为 Swift 的教程项目。我正在实现 MVVM 模式,并且我有一个weightEntry 类,其中一个属性是weight,一个Double

在我看来,我有一个 ViewModel 对象,它有一个 weightEntry 对象。我想将权重文本字段中的条目分配给我的weightEntry.weight,但是我不确定如何在视图中将格式从字符串转换为双精度?

下面是视图中的代码:

    @ObservedObject var mainViewVM = MainViewViewModel()
    
    
    var body: some View {
        VStack(alignment: .leading, spacing: /*@START_MENU_TOKEN@*/nil/*@END_MENU_TOKEN@*/, content: {
            
            
            Text("Weight Tracking App").font(.title)
            
            HStack {
                Text("Add your current weight").font(.subheadline)
                TextField("Weight", text: $mainViewVM.weightEntry.weight)
                    .padding()
                    .keyboardType(.decimalPad)
            }

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    有一个初始化器,它可以采用 Double 和格式描述 init(_:value:format:prompt:)

    TextField("Weight", value: $mainViewVM.weightEntry.weight, format: .number.precision(.fractionLength(1)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      • 2011-08-11
      • 1970-01-01
      相关资源
      最近更新 更多