xcode swift - 将文本格式化为电话号码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27609104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:24:18  来源:igfitidea点击:

xcode swift - formatting text as phone number

iphonexcodeswiftios8

提问by Johnny K

I'm creating an iPhone app using Swift. I'm trying to setup a textfield in which the user can enter a phone number that automatically becomes formatted EXACTLY like it does in the built-in Contacts app as it is typed. I'm hoping xcode has built-in methods for doing this.

我正在使用 Swift 创建一个 iPhone 应用程序。我正在尝试设置一个文本字段,用户可以在其中输入一个电话号码,该电话号码在键入时会自动格式化,就像在内置联系人应用程序中一样。我希望 xcode 具有执行此操作的内置方法。

As an alternative, I created my own code that would add and delete brackets, dashes, etc as the user types and backspaces, but this quickly became problematic if the user was to move the curser away from the end of the entered text. In the Contacts app, if the cursor is moved just after a bracket and the user hits backspace, it deletes not just the bracket but rather the number preceding it. I'm not sure if this is done with some built-in formatting method or if perhaps there is code that replicates the text shown with brackets, dashes, etc removed and reads the position of the cursor, then calculates what the new string should be, and adds new brackets, dashes, etc.

作为替代方案,我创建了自己的代码,可以在用户键入和退格时添加和删除括号、破折号等,但是如果用户要将光标从输入文本的末尾移开,这很快就会出现问题。在联系人应用程序中,如果光标刚好移动到括号之后并且用户按退格键,它不仅会删除括号,还会删除它前面的数字。我不确定这是否是通过一些内置的格式化方法完成的,或者是否有代码可以复制删除了括号、破折号等的文本并读取光标的位置,然后计算新字符串应该是什么, 并添加新的括号、破折号等。

Specifically, I'd like to know:

具体来说,我想知道:

1) Is there a built-in method to format text to look like a phone number exactly as is done in the Contacts app?

1) 是否有一种内置方法可以将文本格式化为与“联系人”应用程序中完全相同的电话号码?

2) If there is no built-in method, can someone tell me how I can have Swift read in the cursor position?

2)如果没有内置方法,有人可以告诉我如何让Swift在光标位置读取吗?

Thanks!

谢谢!

回答by JAL

There is no built-in way to do this. Here's one implementation that uses the UITextField's shouldChangeCharactersInRangemethod:

没有内置的方法可以做到这一点。这是使用UITextField'sshouldChangeCharactersInRange方法的一种实现:

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

        var decimalString = "".join(components) as NSString
        var length = decimalString.length
        var hasLeadingOne = length > 0 && decimalString.characterAtIndex(0) == (1 as unichar)

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

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

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

        var remainder = decimalString.substringFromIndex(index)
        formattedString.appendString(remainder)
        textField.text = formattedString
        return false
    }
    else
    {
        return true
    }
}

As previously answered in this thread: UITextField for Phone Number

正如之前在此线程中回答的那样:UITextField for Phone Number