我想在 SwiftUI 中向 TextField 添加 $ 符号 [英] I want to add $ sign to TextField in SwiftUI

查看:36
本文介绍了我想在 SwiftUI 中向 TextField 添加 $ 符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户键入时向 TextField 添加 $ 符号.

Hi I want to add $ sign to a TextField when a user is typing.

这是我当前的代码.

ZStack(alignment: .leading) {
  if price.isEmpty {
    Text("Enter total budget")
  }
  HStack {
    TextField("", text: $price)
      .keyboardType(.decimalPad)
  }
}

推荐答案

currency formatter 是可行的方法,但如果您只想在键入时在 TextField 中显示 $,您可以使用以下方法:(您当然可以将此方法与格式化程序结合使用)

currency formatter is the way to go, but if you just want to show a $ in the TextField as you type, you could use something like this: (you can of course combine this approach with a Formatter)

struct ContentView: View {
    @State var price = ""
    
    var body: some View {
        VStack {
            ZStack(alignment: .leading) {
                if price.isEmpty {
                    Text("Enter total budget")
                }
                HStack {
                    TextField("", text: Binding(
                        get: { price },
                        set: { newVal in
                        if price.starts(with: "$") {
                            price = newVal
                        } else {
                            price = "$" + newVal
                        }
                    })).keyboardType(.decimalPad)
                }
            }.padding(20)
            Text("number entered: " + String(price.dropFirst()))
        }
    }
}

这篇关于我想在 SwiftUI 中向 TextField 添加 $ 符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆