元组Void(aka())的值没有成员" isSuperset"

时间:2017-06-23 23:48:24

标签: swift textfield nscharacterset

我在两个字符集之间创建了一个联合,以便能够使用带有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)"。怎么纠正?

更新1: 使用当前建议的答案显示错误 enter image description here

更新2: 最近更新 enter image description here

1 个答案:

答案 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中创建的属性,这样你就不会重新创建和联合每次输入字符时都会设置字符集。