我在两个字符集之间创建了一个联合,以便能够使用带有decimalDigits字符集的句点。
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)
}
然而,返回" both.isSuperset(of:characterSet as CharacterSet)"。怎么纠正?
答案 0 :(得分:2)
尝试这样做:
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
}
I found here的基础。
更好的是,使“allowed
”(或“both
”,无论你决定命名它)在viewDidLoad
中创建的属性,这样你就不会重新创建和联合每次输入字符时都会设置字符集。