gpt4 book ai didi

ios - 如何使用 Swift 在文本字段(从右到左)输入货币格式?

转载 作者:行者123 更新时间:2023-11-30 11:13:25 28 4
gpt4 key购买 nike

我有一个数字,比如说0.00

  • 当用户点击 1 时,我们应该得到 0.01
  • 当用户点击 2 时,我们应该显示 0.12
  • 当用户点击 3 时,我们应该显示 1.23
  • 当用户点击 4 时,我们应该显示 12.34

如何使用 Swift 做到这一点?

最佳答案

对于Swift 3。在文本字段中输入货币格式(从右到左)

override func viewDidLoad() {
super.viewDidLoad()

textField.addTarget(self, action: #selector(myTextFieldDidChange), for: .editingChanged)
}

@objc func myTextFieldDidChange(_ textField: UITextField) {

if let amountString = textField.text?.currencyInputFormatting() {
textField.text = amountString
}
}

extension String {

// formatting text for currency textField
func currencyInputFormatting() -> String {

var number: NSNumber!
let formatter = NumberFormatter()
formatter.numberStyle = .currencyAccounting
formatter.currencySymbol = "$"
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2

var amountWithPrefix = self

// remove from String: "$", ".", ","
let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive)
amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.count), withTemplate: "")

let double = (amountWithPrefix as NSString).doubleValue
number = NSNumber(value: (double / 100))

// if first number is 0 or all numbers were deleted
guard number != 0 as NSNumber else {
return ""
}

return formatter.string(from: number)!
}
}

关于ios - 如何使用 Swift 在文本字段(从右到左)输入货币格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51966539/

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