I created a union between two character sets to be able to use a period with the decimalDigits character set.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let allowed = CharacterSet.decimalDigits
let period = CharacterSet.init(charactersIn: ".")
let both = CFCharacterSetUnion(allowed as! CFMutableCharacterSet, period as CFCharacterSet)
let characterSet = NSCharacterSet(charactersIn: string)
return both.isSuperset(of: characterSet as CharacterSet)
}
however, returning "both.isSuperset(of: characterSet as CharacterSet)". how to correct?
Update 1:
Errors displayed with the current suggested answer
Try doing this instead:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var allowed = CharacterSet.decimalDigits
let period = CharacterSet.init(charactersIn: ".")
allowed.formUnion(period)
//UNCOMMENT when isSuperset is working
//let characterSet = CharacterSet(charactersIn: string)
//return allowed.isSuperset(of: characterSet)
// Swift 3 appropriate solution
let isSuperset = string.rangeOfCharacter(from: allowed.inverted) == nil
return isSuperset
}
the basis for which I found here.
Even better, make "allowed
" (or "both
", whatever you decide to name it) a property that gets created in viewDidLoad
so you don't recreate and union the character sets each time a character is typed.