2017-01-16 53 views
0

我想格式化用戶輸入電話號碼。我實施了這個:格式化電話號碼無法正常工作

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.

這裏有什麼問題?

+0

我只是建議你使用委託方法。 –

回答

1

你不似乎已經設置委託您的文本字段:

phoneNumberTextField.delegate = self

和你的ViewController犯規似乎符合了UITextFieldDelegate,如:

class ViewController: UIViewController, UITextFieldDelegate {

而且,它永遠不會是零,所以只是改變它var phoneNumberTextField : UITextField!

+0

無法分配值鍵入Viewcontroller鍵入UITextField – Sam

+0

感謝它工作:) – Sam