我有一个UITextField,我正在尝试将其格式化为电话号码,但是由于某些原因我正在努力获取UITextField的第一个字母。
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
)
修改:我尝试在textField的文本开头添加默认的+
符号(数字为+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
}
答案 0 :(得分:2)
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
}