当我在我的文本字段中键入电话号码时,该号码每次都会复制他自己,例如:我在键盘上键入数字5,它将添加55而不是5,请查找在我的代码下面
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if textField == phoneUser
{
let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
let components = newString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)
let decimalString : String = components.joinWithSeparator("")
let length = decimalString.characters.count
let decimalStr = decimalString as NSString
let hasLeadingOne = length > 0 && decimalStr.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 = decimalStr.substringWithRange(NSMakeRange(index, 3))
formattedString.appendFormat("(%@)", areaCode)
index += 3
}
if length - index > 3
{
let prefix = decimalStr.substringWithRange(NSMakeRange(index, 3))
formattedString.appendFormat("%@-", prefix)
index += 3
}
let remainder = decimalStr.substringFromIndex(index)
formattedString.appendString(remainder)
textField.text = formattedString as String
}
//-----------------------------------------------------------------------------
//length of max characteres for uitextfield and lowercase
//-----------------------------------------------------------------------------
Username.autocapitalizationType = UITextAutocapitalizationType.None
if string.characters.count == 0 {
return true
}
let currentText = textField.text ?? ""
let prospectiveText = (currentText as NSString).stringByReplacingCharactersInRange(range, withString: string.lowercaseString)
if let _ = string.rangeOfCharacterFromSet(NSCharacterSet.uppercaseLetterCharacterSet()) {
// Do not allow upper case letters
return false
}
switch textField {
case Name:
return prospectiveText.doesNotContainCharactersIn("0123456789") &&
prospectiveText.characters.count <= 34
case website:
return prospectiveText.characters.count <= 34
case aboutUser:
return prospectiveText.characters.count <= 64
default:
return true
}
}
答案 0 :(得分:0)
此委托方法的规则非常简单:如果您返回true
,则不得同时设置文本字段的文本。如果你这样做,一切都会发生两次。