I have a text field that calls a method to format the input as a percentage in an as-you-type fashion.
cell.textField.addTarget(self, action: #selector(textChangedIntoPercent(sender:)), for: .editingChanged)
The method called:
@objc func textChangedIntoPercent (sender : UITextField) {
if let amountString = sender.text?.percentInputFormatting() {
sender.text = amountString
}
}
The following code works well when entering numbers with the trailing % sign. However, when using backspace, nothing is deleted, the string just returns itself, and the last number is not backspaced. If I change the position of the cursor to just before the percent sign, I am able to delete the numbers.
func percentInputFormatting() -> String {
var number: NSNumber!
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
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.count), withTemplate: "")
let double = (amountWithPrefix as NSString).doubleValue
number = NSNumber(value: (double / 100))
guard number != 0 as NSNumber else {
return "0%"
}
return "\(formatter.string(from: number)!)" + "%"
}