我必须在textfield 92 123 0123456789中使用此模式。创建一个文本字段以获取其中的电话号码。在属性检查器中,我已经将键盘类型设置为数字键盘,而在文本中我给出了从0123456789
获取数字的模式。当我运行一个应用程序并首先输入任何值时,它也需要字母表,我的模式也无法正常工作。我们如何才能做到这一点只取数字和值模式中的值应该只使用这种模式923330123456789
,因为它不应该在92之前取+或00。
答案 0 :(得分:1)
您需要实施textField delegate
之类的内容,
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
// allow back space
if (string.length == 0) {
return YES;
}
NSCharacterSet *set = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
if (([string rangeOfCharacterFromSet:set].location != NSNotFound) ) {
return NO;
}
if (range.location == 0 && ![string isEqual: @"9"]) {
return NO;
}
if (range.location == 1 && ![string isEqual: @"2"]) {
return NO;
}
return YES;
}
并且不要忘记设置
yourTextField.delegate = self;
在viewDidload
。
更新:
您可以显示类似的警告
if (range.location == 0 && ![string isEqual: @"9"]) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"First character must be 9" message:@"" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show]; // It's for demo. `UIAlertView` is deprecated , you can use `UIAlertController` instead
return NO;
}
答案 1 :(得分:0)
你走了:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
newString = [newString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:string];
BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
if(!stringIsValid)
return stringIsValid;
int length = (int)newString.length;
if(newString.length > 0 && newString.length < 3)
{
// Need to check if first two character 9 or 92.
NSString *firstTwoChar=[newString substringToIndex:length];
if([firstTwoChar isEqualToString:@"9"] || [firstTwoChar isEqualToString:@"92"])
return TRUE;
else
return FALSE;
NSLog(@"%@",firstTwoChar);
}
return YES;
}