动态格式化数字以在UITextField中包含逗号

时间:2018-02-08 07:30:18

标签: ios swift3 uitextfield

如何将价格文本字段文本格式化为234,345,567等货币格式,并且我还需要将小数点限制为不超过2,并在用户开始输入时附加$符号。

例如:$ 234,345,678.25

像这样我想在文本字段中键入数量时在3个数字之间添加逗号

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {


if ((string == "0" || string == "") && (txtFldPostalCode.text! as NSString).range(of: ".").location < range.location) {
  return true
}
let cs = NSCharacterSet(charactersIn: "0123456789.").inverted
let filtered = string.components(separatedBy: cs)
let component = filtered.joined(separator: "")
let isNumeric = string == component
if isNumeric {
  let formatter = NumberFormatter()
  formatter.numberStyle = .decimal
  formatter.maximumFractionDigits = 8
  let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
  let numberWithOutCommas = newString.replacingOccurrences(of: ",", with: "")
  let number = formatter.number(from: numberWithOutCommas)
  if number != nil {
    var formattedString = formatter.string(from: number!)
    if string == "." && range.location == textField.text?.length {
      formattedString = formattedString?.appending(".")
    }
    textField.text = formattedString
  } else {
    textField.text = nil
  }
}
return false

}

1 个答案:

答案 0 :(得分:2)

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

@IBOutlet weak var textfield: UITextField!


override func viewDidLoad() {
    super.viewDidLoad()

    textfield.addTarget(self, action: #selector(myTextFieldDidChange), for: .editingChanged)
    // Do any additional setup after loading the view.
}
@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

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

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


    guard number != 0 as NSNumber else {
        return ""
    }

    return formatter.string(from: number)!
}

希望这有用......