Here’s what I came up with:
//MARK: - Keyboard Methods
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
//Disallow multiple decimal places from being entered into the text field
let existingTextHasDecimalSeparator = textField.text?.range(of: ".")
let replacementTextHasDecimalSeparator = string.range(of: ".")
//This will check to ensure only the numbers in the below character set are allowed
let allowedCharacters = CharacterSet(charactersIn: "0123456789.")
for scalar in string.unicodeScalars {
if allowedCharacters.contains(scalar) {
if existingTextHasDecimalSeparator != nil, replacementTextHasDecimalSeparator != nil {
return false
} else {
return true
}
} else {
return false
}
}
return true
}