我想使用货币格式化程序来设置带逗号的金额和带限制的小数,字符也不应超过 10,$ 应首先出现。代码示例如下,但不适用于十进制。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var newLength = 10
if textField == donateAmountTextfield {
let text = donateAmountTextfield.text!
newLength = text.characters.count + string.characters.count - range.length
}
return newLength <= 10 // Bool
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField == donateAmountTextfield {
if donateAmountTextfield.text != "" {
dollerSign.isHidden = true
if let amountString = donateAmountTextfield.text?.currencyInputFormatting() {
donateAmountTextfield.text = amountString
}
} else {
dollerSign.isHidden = false
}
} else if textField == enterCardNumber {
if validateData.validateDonation((donateAmountTextfield?.text)! as String) {
self.view.makeToast("Please enter valid Donation amount", duration: 5.0, position: CSToastPositionCenter)
}
}
}
格式化程序类-
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.characters.count), withTemplate: "")
let double = (amountWithPrefix as NSString).doubleValue
number = NSNumber(value: (double / 1))
// if first number is 0 or all numbers were deleted
guard number != 0 as NSNumber else {
return ""
}
return formatter.string(from: number)!
}
}
IBtextFieldName.text = self.formatCurrency(strAmount: strAmount) //In viewDidLoad
func formatCurrency(strAmount strAmount: String) -> String {
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
formatter.locale = NSLocale(localeIdentifier: "en_US")
let numberFromField = (NSString(string: strAmount).doubleValue)/100
return formatter.stringFromNumber(numberFromField)!
}
//For character should not exceed by 10
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let newCharLength = textField.text!.characters.count + string.characters.count - range.length
if newCharLength >= 10 {
return false
}
}