2016-03-16 125 views
0

我有一個UITextField,我試圖將其格式化爲電話號碼,但是我掙扎得到UITextField的第一個字母出於某種原因。UITextField shouldChangeCharactersInRange不檢測第一個字符

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool 
{ 
    if textField == myTextField { 
    var updatedTextString : NSString = PartialFormatter().formatPartial(textField.text!) 

    self.formattedPhoneNumber(updatedTextString, textField: textField) 
    } 
return true 
} 

func formattedPhoneNumber(updatedTextString: NSString, textField: UITextField) { 
    textField.text = updatedTextString as String 
    print(updatedTextString) 
} 

我在做什麼錯?

請注意,我爲了使用PhoneNumberKit格式化電話號碼(與使用PartialFormatter().formatPartial


編輯:我試着在文本框的文本的開頭添加一個默認+符號(如數字+44 ..)

var updatedTextString : NSString = PartialFormatter().formatPartial("+\(textField.text!)") 

但它完全錯了。它首先保持打印++++,然後修復4個或更多字符。

如此這般像...

I press 1 - `+1` on UITextField - `+` on console 
then press 5 - `++15` on UITextField - `++1` on console 
then press 6 - `+++156` on UITextField - `+++15` on console 

then press 8 - `+1568` on UITextField - `+1 56` on console 
    // so it magically fixed itself after 4 chars. 

Also removing everything leaves `+++` on UITextField and `++++` on console 
and doesn't delete more 

我在做什麼錯?


編輯2:

我嘗試使用下面張貼的答案。但現在,它只是簡單的數字。他們不與PartialFormatter().formatPartial()

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool 
{ 
    if textField == myTextField { 
    let textString : NSString = textField.text! 
    let candidateString : NSString = textString.stringByReplacingCharactersInRange(range, withString: string)  
    let updatedTextString : NSString = PartialFormatter().formatPartial(candidateString as String) 

    self.formattedPhoneNumber(updatedTextString, textField: textField) 
    } 
    return true 
} 

回答

1

分組的shouldChangeCharactersInRange()函數是要求改變是否應適用,但尚未允許您的文本字段進行修改。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool 
{ 
    if textField == myTextField { 
    let textString : NSString = textField.text! 
    let candidateString : NSString = textString.stringByReplacingCharactersInRange(range, withString: string)  
    let updatedTextString : NSString = PartialFormatter().formatPartial(candidateString as String) 
    print(updatedTextString) 
    textField.text = updatedTextString 
    } 
    return true 
} 
+0

我讓你的例子工作並編輯你的答案。但是,它現在不會將數字分組爲'PartialFormatter()。formatPartial'預計會做;它只顯示簡單的數字。但是,現在檢測字符工作正常 – senty

相關問題