gpt4 book ai didi

swiftui - 将文本字段格式化为 2 位小数而不输入小数(SwiftUI)

转载 作者:行者123 更新时间:2023-12-04 01:38:17 27 4
gpt4 key购买 nike

在文本字段中,我想,当用户输入一个数字时,例如12345,它被格式化为 123.45。用户永远不需要输入小数位,它只使用最右边的 2 个数字作为小数位。该字段也应该只允许数字。这是针对 SwiftUI 项目的。提前感谢您的任何帮助。

最佳答案

由于您输入的内容和 TextField View 中显示的内容之间存在两种方式的绑定(bind),因此似乎无法对输入的显示数字进行插值。我建议一个小技巧:

  • 创建一个叠加了 TextField 和 Text View 的 ZStack。
  • TextField 中输入文本的前景字体为透明或白色 .foregroundColor(.clear)
  • 键盘只有数字,没有小数点:.keyboardType(.numberPad)
  • 使用 .accentColor(.clear)隐藏光标
  • 结果显示在 TextView 中,格式为 specifier: "%.2f"

  • 它看起来像



    这是代码:
    struct ContentView: View {
    @State private var enteredNumber = ""
    var enteredNumberFormatted: Double {
    return (Double(enteredNumber) ?? 0) / 100
    }
    var body: some View {

    Form {
    Section {
    ZStack(alignment: .leading) {
    TextField("", text: $enteredNumber)
    .keyboardType(.numberPad).foregroundColor(.clear)
    .textFieldStyle(PlainTextFieldStyle())
    .disableAutocorrection(true)
    .accentColor(.clear)
    Text("\(enteredNumberFormatted, specifier: "%.2f")")
    }
    }
    }
    }
    }

    关于swiftui - 将文本字段格式化为 2 位小数而不输入小数(SwiftUI),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58605993/

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