我使用TextField从特定形式的xxx-xxx-xx-xx中获取用户编号。
我需要显示用户NumberPad键盘和添加分隔符"-",在编辑期间的3,6和8位数字。
问题是,当我指定
TextField.keyboardType = UIKeyboardType.NumberPad和添加分隔符在我的textFieldDidChange方法中,TextField停止响应添加下一个字符或删除。
更改为UIKeyboardType.Default可以正常工作,但键盘不只是数字。
发布于 2016-05-25 18:30:56
您好,您可以使用以下代码。
txtField.keyboardType = UIKeyboardTypeNumberPad;
- (BOOL)textFieldPhoneDigit:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
@try
{
NSString *filter = @"(###) - (###) - (####)"; //Change Fileter As Per requirement.
if(!filter) return YES; // No filter provided, allow anything
NSString *changedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if(range.length == 1 && // Only do for single deletes
string.length < range.length &&
[[textField.text substringWithRange:range] rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"0123456789"]].location == NSNotFound)
{
// Something was deleted. Delete past the previous number
NSInteger location = changedString.length-1;
if(location > 0)
{
for(; location > 0; location--)
{
if(isdigit([changedString characterAtIndex:location]))
{
break;
}
}
changedString = [changedString substringToIndex:location];
}
}
textField.text = filteredPhoneStringFromStringWithFilter(changedString, filter);
return NO;
}
@catch (NSException *exception) {
NSLog(@"Exception shouldChange %@",[exception description]);
}发布于 2016-05-25 18:34:12
在下面的UITextField委托方法下面使用此方法,
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == numberTextField)
{
if (range.location == 12) {
return NO;
}
// Reject appending non-digit characters
if (range.length == 0 &&
![[NSCharacterSet decimalDigitCharacterSet] characterIsMember:[string characterAtIndex:0]]) {
return NO;
}
// Auto-add hyphen before appending 4rd or 7th digit or 10th digit
if (range.length == 0 &&
(range.location == 3 || range.location == 7 || range.location == 10)) {
textField.text = [NSString stringWithFormat:@"%@-%@", textField.text, string];
return NO;
}
// Delete hyphen when deleting its trailing digit
if (range.length == 1 &&
(range.location == 4 || range.location == 8)) {
range.location--;
range.length = 2;
textField.text = [textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
return YES;
}
return YES;
}希望能对你有所帮助
发布于 2016-05-25 19:06:58
在shouldChangeCharactersInRange中,方法运行得很好。谢谢。
https://stackoverflow.com/questions/37434008
复制相似问题