格式化电话号码不能正常工作

时间:2017-01-16 11:27:45

标签: ios swift

我正在尝试格式化用户输入的电话号码。我实现了这个:

import UIKit

class ViewController: UIViewController {
var phoneNumberTextField : UITextField?
var docController: UIDocumentInteractionController?

override func viewDidLoad() {
    super.viewDidLoad()
    phoneNumberTextField = UITextField(frame: CGRectMake(10, 150, 100, 50))
    phoneNumberTextField?.backgroundColor = UIColor.brownColor()
    self.view.addSubview(phoneNumberTextField!)


}

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

        let decimalString = components.joinWithSeparator("") as NSString
        let length = decimalString.length
        let hasLeadingOne = length > 0 && decimalString.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 = decimalString.substringWithRange(NSMakeRange(index, 3))
            formattedString.appendFormat("(%@)", areaCode)
            index += 3
        }
        if length - index > 3
        {
            let prefix = decimalString.substringWithRange(NSMakeRange(index, 3))
            formattedString.appendFormat("%@-", prefix)
            index += 3
        }

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

来自Here。当我运行应用程序并开始添加数字时,没有任何反应。没有出现括号和大肆宣传。我想将(197)-444-4444转换为1974444444。

这里有什么问题?

1 个答案:

答案 0 :(得分:1)

您似乎没有为文本字段设置委托:

phoneNumberTextField.delegate = self

并且你的viewcontroller似乎不符合UITextFieldDelegate之类:

class ViewController: UIViewController, UITextFieldDelegate {

此外,它永远不会是零,所以只需将其更改为var phoneNumberTextField : UITextField!