Here is my crack at it… a little messy maybe, but at a quick glance it’s a little different than what’s been posted so far. But this code does work.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let invertedSet = NSCharacterSet(charactersIn:"0123456789").inverted
let components = string.components(separatedBy: invertedSet)
let filtered = components.joined(separator: "")
if filtered == string {
return true
} else {
if string == "." {
let numberofdots = textField.text!.components(separatedBy:".").count
if numberofdots == 1 {
return true
} else {
if numberofdots > 1 && string == "." {
return false
} else {
return true
}
}
} else {
return false
}
}
}