带占位符的电话号码的UITextField

时间:2016-06-22 04:25:25

标签: swift2 uitextfield ios9.3

我正在使用其他帖子的下面代码来格式化UITextField美国的电话号码,但是当用户开始输入而不是清除文本时,我希望占位符保留。例如。键入后+1(XXX)XXX-XXXX应该像+1(23X)XXX-XXXX。 我没有完全清除占位符,而是希望它作为用户指南。

我目前正在使用的代码:

    func textFieldDidBeginEditing(textField: UITextField) {
    if (textField == self.mobileNumberTextField) {
        textField.text = "+"
    }
}

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if (textField == self.mobileNumberTextField) {
        let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

        if (newString.characters.count < textField.text?.characters.count && newString.characters.count >= 1) {
            return true                                                         // return true for backspace to work
        } else if (newString.characters.count < 1) {
            return false;                        // deleting "+" makes no sence
        }
        if (newString.characters.count > 17 ) {
            return false;
        }

        let components = newString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)

        let decimalString = components.joinWithSeparator("") as NSString
        let length = decimalString.length

        var index = 0
        let formattedString = NSMutableString()
        formattedString.appendString("+")

        if (length >= 1) {
            let countryCode = decimalString.substringWithRange(NSMakeRange(0, 1))
            formattedString.appendString(countryCode)
            index += 1
        }

        if (length > 1) {
            var rangeLength = 3
            if (length < 4) {
                rangeLength = length - 1
            }
            let operatorCode = decimalString.substringWithRange(NSMakeRange(1, rangeLength))
            formattedString.appendFormat(" (%@) ", operatorCode)
            index += operatorCode.characters.count
        }

        if (length > 4) {
            var rangeLength = 3
            if (length < 7) {
                rangeLength = length - 4
            }
            let prefix = decimalString.substringWithRange(NSMakeRange(4, rangeLength))
            formattedString.appendFormat("%@-", prefix)
            index += prefix.characters.count
        }

        if (index < length) {
            let remainder = decimalString.substringFromIndex(index)
            formattedString.appendString(remainder)
        }

        textField.text = formattedString as String

        if (newString.characters.count == 17) {
            textField.resignFirstResponder()
        }

        return false
    }

    return true
}

1 个答案:

答案 0 :(得分:1)

我建议你在textfield中使用默认文本。您可以使用占位符执行相同操作,我认为

将此默认字符串视为字符数组。您应该跟踪按下的每个键,并使用输入的子字符串(在默认字符串中的该索引处)替换默认字符串中索引处的字符。当删除字符时,应该用该字符(X)替换。

尝试类似:

var defaultstring = "+1 (XXX) XXX-XXXX"
var yourtextField = UITextField()

override func viewDidLoad() {
  yourtextField.text = defaultstring
}

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
   if string != "" {
        var range = self.defaultstring.rangeOfString("X")

        self.defaultstring.replaceRange(range!, with: string)
        self.yourtextField.text = self.defaultstring
// I tested, this is working. 
    }

    else if substring == "" {
        // THis case if when user presses backspace.. 
        let idx = self.defaultstring.characters.indexOf("X")?.advancedBy(-1)
        let range = self.defaultstring.rangeOfComposedCharacterSequenceAtIndex(idx!)
        self.defaultstring.replaceRange(range, with: "X")

    }

}

此代码可以使用,但有些事情需要注意,例如: 结束案例,其中用户键入的字符数多于允许的字符数 仅替换&#34; X&#34;已键入字符已被处理 如果用户使用backSpace,它将起作用,但是如果范围提前-1并且下一个字符必须替换是&#34; - &#34;,那么你应该检查它并再次前进-1,所以要替换的角色肯定是X

提出问题以获取任何细节。