Here is what I have come up with for the Bronze solution. I use NSCharacterSet.decimalDigits to create a test range [I also insert a decimal point ‘.’] - I needed this for it to work correctly, not sure if this is only required for keyboard input vs. touch-screen input. I was challenged with observing delete, so I ran a test for empty ‘string’ variable - …
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
let existingTextHasDecimalSeperator = textField.text?.range(of: ".")
let replacementTextHasDecimalSeperator = string.range(of: ".")
var validTextFieldInput = NSCharacterSet.decimalDigits // Create range with only decimal digits
validTextFieldInput.insert(".") // Add the decimal character (in case using Keyboard?)
// Create test variable for replacement text against valid input range
let replacementTextIsOnlyNumbers = string.rangeOfCharacter(from: validTextFieldInput)
if string == "" { // If valid number or backspace ("")
return true
} else {
if replacementTextIsOnlyNumbers != nil {
if existingTextHasDecimalSeperator != nil,
replacementTextHasDecimalSeperator != nil {
return false
}
return true
}
return false
}
}