ios - UITextField 货币格式从左到右

标签 ios swift uitextfield number-formatting

我想在输入金额时将 UITextField 格式化为左侧有一个 $

到目前为止,我的代码所做的是,当我输入 let say $5.65 时,输入方式如下: $0.05 -> $0.56 -> $5.65

我希望它不是从右到左,而是从左到右,如下所示:$5 -> $5. -> $5.6 -> 5.65 美元

但我想将其限制为仅两位小数,美元符号位于左侧,并且您不能输入任何其他字符(例如:!,@,#,$,%,^, A-Z' )

这是我目前拥有的:

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

    let text: NSString = (textField.text ?? "") as NSString
    let finalString = text.replacingCharacters(in: range, with: string)

    // 'currency' is a String extension that doews all the number styling
    amuTextField.text = finalString.currency

    // returning 'false' so that textfield will not be updated here, instead from styling extension
    return false
}

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.characters.count), withTemplate: "")

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

    return formatter.string(from: number)!
}

最佳答案

您可以使用它来限制 . 之后的小数位数:

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

      guard let oldText = textField.text, let r = Range(range, in: oldText) else {
        return true
      }

      let newText = oldText.replacingCharacters(in: r, with: string)
      let isNumeric = newText.isEmpty || (Double(newText) != nil)
      let numberOfDots = newText.components(separatedBy: ".").count - 1

      let numberOfDecimalDigits: Int
      if let dotIndex = newText.firstIndex(of: ".") {
        numberOfDecimalDigits = newText.distance(from: dotIndex, to: newText.endIndex) - 1
      } else {
        numberOfDecimalDigits = 0
      }

      return isNumeric && numberOfDots <= 1 && numberOfDecimalDigits <= 2
  }

关于ios - UITextField 货币格式从左到右,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53672583/

相关文章:

ios - 我可以在 Interface Builder 中设计一个带有静态内容的 UITableViewController 吗?

ios - 墙上的 SceneKit 阴影

ios - 如何设置文本字段的样式?

ios - 多个DCSliders发送不同的控制值(Xcode)

iphone - iOS 智能应用横幅 - 在 iPad 上显示,而不是在 iPhone 上显示

ios - 从 InAppBrowser 在 native 浏览器中打开链接

ios - 选择 TableView 单元格时(一次)无法触发segue

objective-c - 从 Swift 调用 Objective C setter 方法时“没有成员”

iphone - Xcode : UITextfield uneditable

ios - UITextfield 子类没有响应 insertText : method of UIKeyInput protocol