当我在文本字段中键入电话号码时,该数字每次都会重复自我,例如:我在键盘中键入数字5时,它将添加55而不是5,请在我的代码下面查找

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField == phoneUser
    {
        let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
        let components = newString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)

        let decimalString : String = components.joinWithSeparator("")
        let length = decimalString.characters.count
        let decimalStr = decimalString as NSString
        let hasLeadingOne = length > 0 && decimalStr.characterAtIndex(0) == (1 as unichar)

        if length == 0 || (length > 10 && !hasLeadingOne) || length > 11
        {
            let newLength = (textField.text! as NSString).length + (string as NSString).length - range.length as Int

            return (newLength > 10) ? false : true
        }
        var index = 0 as Int
        let formattedString = NSMutableString()

        if hasLeadingOne
        {
            formattedString.appendString("1 ")
            index += 1
        }
        if (length - index) > 3
        {
            let areaCode = decimalStr.substringWithRange(NSMakeRange(index, 3))
            formattedString.appendFormat("(%@)", areaCode)
            index += 3
        }
        if length - index > 3
        {
            let prefix = decimalStr.substringWithRange(NSMakeRange(index, 3))
            formattedString.appendFormat("%@-", prefix)
            index += 3
        }

        let remainder = decimalStr.substringFromIndex(index)
        formattedString.appendString(remainder)

        textField.text = formattedString as String
    }

    //-----------------------------------------------------------------------------
    //length of max characteres for uitextfield and lowercase
    //-----------------------------------------------------------------------------
    Username.autocapitalizationType = UITextAutocapitalizationType.None
    if string.characters.count == 0 {
        return true
    }
    let currentText = textField.text ?? ""
    let prospectiveText = (currentText as NSString).stringByReplacingCharactersInRange(range, withString: string.lowercaseString)
    if let _ = string.rangeOfCharacterFromSet(NSCharacterSet.uppercaseLetterCharacterSet()) {
        // Do not allow upper case letters
        return false
    }

    switch textField {
    case Name:
        return prospectiveText.doesNotContainCharactersIn("0123456789") &&
        prospectiveText.characters.count <= 34
    case website:
        return prospectiveText.characters.count <= 34
    case aboutUser:
        return prospectiveText.characters.count <= 64
    default:
        return true
    }
}

最佳答案

此委托方法的规则非常简单:如果返回true,则也不能同时设置文本字段的文本。如果这样做,一切都会发生两次。

08-06 00:56