Tuesday, November 24, 2015

Add Hyphen in UITextfield (auto add hyphen and parentheses) - in Swift2


func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
    sendButton.enabled = true
    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
    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
    return false

}

By using this you can achieve both restrict phone number to 10 digit and format it as per US format.

No comments:

Post a Comment