I wrote some code that formats a textfield to include numbers only, thousands separators and limit amount of digits to 30, was wondering if someone can make some improvements on it reduce the code, fix bugs if there are any and if there is a more efficient way to use such code with multiple fields.
Code:
import Foundation
import Cocoa
class sampleclass: NSObject, NSTextFieldDelegate {
@IBOutlet weak var MyTextField: NSTextField!
var StringBeingChanged = ""
override func controlTextDidChange(_ notification:Notification) {
if notification.object as? NSTextField == MyTextField {
//format the field
self.FormatSelectedField()
}
}
func FormatSelectedField() {
//make textfield numbers and decimal only
let aSet = CharacterSet(charactersIn:"0123456789.").inverted
MyTextField.stringValue = MyTextField.stringValue.components(separatedBy: aSet).joined(separator: "")
//limit field to 30 digits
if MyTextField.stringValue.characters.count > 30 {
MyTextField.stringValue = String(MyTextField.stringValue.characters.dropLast((MyTextField.stringValue.characters.count - 30)))
}
// numberformatter
let numberFormatter: NumberFormatter = NumberFormatter()
numberFormatter.groupingSeparator = ","
numberFormatter.groupingSize = 3
numberFormatter.usesGroupingSeparator = true
numberFormatter.maximumFractionDigits = 30
numberFormatter.decimalSeparator = "."
let character = "."
//value before format for later use
StringBeingChanged = MyTextField.stringValue
//format textfield
MyTextField.stringValue = numberFormatter.string(for: NSDecimalNumber(string: MyTextField.stringValue))!
// if original value contains decimal and new value does not, add a decimal to new value
if !(MyTextField.stringValue.characters.contains(".")) && (StringBeingChanged.characters.contains(".")) {
MyTextField.stringValue = String(format: "%@%@", MyTextField.stringValue, character)
}
let string1 = 0.00
let string2 = 0.00
let subtract = 0.00
//count number of zeroes after format
string1 = Double(MyTextField.stringValue.components(separatedBy: "0").count)
//count number of zeroes before format
string2 = Double(StringBeingChanged.components(separatedBy: "0").count)
//get the number of zeroes missing
subtract = string2 - string1
//add missing zeroes
if string2 > string1 {
MyTextField.stringValue = "\(MyTextField.stringValue)\("".padding(toLength: Int(subtract), withPad: "0", startingAt: 0))"
}
}
}