我试图显示 Double 中的单个值

Cra*_*ine 1 text stepper swiftui

我正在尝试显示来自步进器的单个值。

显示步进器在文本解释中显示双精度值。

例如,我将值 litreValue 设置为 Double,然后使用步进器可以选择一个值,例如 8,但我希望它在文本字段中仅显示为 8,而不是 8.000000。

我尝试过 Text("(NSString(format: "%.2f", litreValue))") 但出现错误。

有什么建议请。

import SwiftUI

struct ContentView: View {
  @State private var litreValue : Double = 0.00
  @State private var selection = 0
  let mixRatio = ["10:1","15:1","20:1","25:1","30:1","35:1","40:1","45:1","50:1","55:1","60:1","65:1","70:1"]
  var body: some View {

    VStack{

      ZStack{
        RoundedRectangle(cornerRadius: /*@START_MENU_TOKEN@*/20/*@END_MENU_TOKEN@*/)
          .foregroundColor(/*@START_MENU_TOKEN@*/.blue/*@END_MENU_TOKEN@*/)
          .frame(width: 300.0, height: 200.0)
          .shadow(radius: /*@START_MENU_TOKEN@*/10/*@END_MENU_TOKEN@*/)
        VStack {
          Image("Fuel-Icon2")
            .resizable()
            .frame(width: /*@START_MENU_TOKEN@*/100.0/*@END_MENU_TOKEN@*/, height: /*@START_MENU_TOKEN@*/100.0/*@END_MENU_TOKEN@*/)
          Text("Fuel Mix")
            .font(.largeTitle)
        }
      }

      VStack {
        Stepper(value: $litreValue, in: 1...200) {
          Text("Litres")
            .font(.title)
        }.padding(.top, -30)
        ZStack{
          RoundedRectangle(cornerRadius: /*@START_MENU_TOKEN@*/20/*@END_MENU_TOKEN@*/)
            .foregroundColor(.gray)
            .frame(width: 300.0, height: 50.0)


          // Display as Single Digit example 2, or 3, or 7 etc
          Text("\(litreValue)")



            .font(.largeTitle)
            .fontWeight(.semibold)
        }
      }.padding(30)

      VStack{
        Picker(selection: $selection, label:
          Text("")
            .padding(.top))
        {
          ForEach(0 ..< mixRatio.count) { index in
            Text(self.mixRatio[index]).tag(index)

          }
        }
      }
      .padding(.top, -60)
      .padding(.horizontal, 50)
Run Code Online (Sandbox Code Playgroud)

sfu*_*ng3 5

如果您希望显示整数而不是双精度数,可以将其转换为整数然后显示。

Text("\(Int(litreValue))")
Run Code Online (Sandbox Code Playgroud)