我在UI文本字段中获取电话卡号表单用户。数字的格式类似于
123-4567-890
我希望用户自动键入123 - 在4567之后插入UITextField
- 依此类推。
我是使用UITextField
委托方法中的以下代码完成的:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
NSLog(@"***** %d",textField.text.length);
if(textField.text.length == 3)
{
textField.text = [textField.text stringByAppendingString:@"-"];
}
return YES;
}
但问题在澄清文本时提出,当我们开始清算时。
最后3位数字890清除然后 - 添加,我们清除它并再次添加和soooo on so清除停止
我们使用
一次清除所有文字textField.clearButtonMode = UITextFieldViewModeWhileEditing; //To clear all text at a time
但我们的要求是用户必须一次删除一个字符。
如何实现它?
答案 0 :(得分:3)
在结算期间,replacementString
应为空@""
。因此,除了长度检查之外,还应检查替换字符串。像这样:
if (textField.text.length == 3 && ![string isEqualToString:@""]) {
// append -
}
答案 1 :(得分:1)
使用:我在这个论坛的某个地方看过这个,它对我有用
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *filter = @"###-####-###";
if(!filter) return YES;
NSString *changedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if(range.length == 1 && string.length < range.length && [[textField.text substringWithRange:range] rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"0123456789"]].location == NSNotFound)
{
NSInteger location = changedString.length-1;
if(location > 0)
{
for(; location > 0; location--)
{
if(isdigit([changedString characterAtIndex:location]))
break;
}
changedString = [changedString substringToIndex:location];
}
}
textField.text = filteredStringFromStringWithFilter(changedString, filter);
return NO;
}
NSString *filteredStringFromStringWithFilter(NSString *string, NSString *filter)
{
NSUInteger onOriginal = 0, onFilter = 0, onOutput = 0;
char outputString[([filter length])];
BOOL done = NO;
while(onFilter < [filter length] && !done)
{
char filterChar = [filter characterAtIndex:onFilter];
char originalChar = onOriginal >= string.length ? '\0' : [string characterAtIndex:onOriginal];
switch (filterChar) {
case '#':
if(originalChar=='\0')
{
done = YES;
break;
}
if(isdigit(originalChar))
{
outputString[onOutput] = originalChar;
onOriginal++;
onFilter++;
onOutput++;
}
else
{
onOriginal++;
}
break;
default:
outputString[onOutput] = filterChar;
onOutput++;
onFilter++;
if(originalChar == filterChar)
onOriginal++;
break;
}
}
outputString[onOutput] = '\0';
return [NSString stringWithUTF8String:outputString];
}