我在两个字符集之间创建了一个联合,以便能够使用带有 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)”。如何纠正?
最佳答案
尝试这样做:
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
中创建的属性> 这样您就不会在每次键入字符时都重新创建和合并字符集。
关于swift - 元组 Void (aka ()) 的值没有成员 "isSuperset",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44731355/