我正在创建一个文本字段。
但是文本字段应该只包含字母而不是数字。如何在ios中执行此操作而不检查ASCII值?
答案 0 :(得分:2)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
BOOL canEdit=NO;
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"];
for (int i = 0; i < [string length]; i++)
{
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c])
{
canEdit=NO;
}
else
{
canEdit=YES;
}
}
return canEdit;
}
答案 1 :(得分:1)
以上所有答案都告诉我们如何只允许使用字母表,如果用户按下BackSpace怎么办? 这是我的解决方案:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
const char * _char = [string cStringUsingEncoding:NSUTF8StringEncoding];
int isBackSpace = strcmp(_char, "\b");
if (isBackSpace == -8) {
NSLog(@"Backspace was pressed");
return YES;
}
BOOL canEdit=NO;
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz or all Character set you like!!!"];
for (int i = 0; i < [string length]; i++)
{
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c])
{
canEdit=NO;
}
else
{
canEdit=YES;
}
}
return canEdit;
}
答案 2 :(得分:0)
您需要使用委托方法shouldChangeTextInRange
- 每次文本更改时系统会自动调用它。在这种方法中,你需要像这样审查textField中的输入。
为了调用此方法,您需要声明您的类在类.h文件中实现协议(即@interface MyClass : UIViewController <UITextFieldDelegate>
),并将文本字段的委托设置为您的类的实例。 / p>
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"] invertedSet];
NSString *trimmedReplacement =
[[ text componentsSeparatedByCharactersInSet:nonNumberSet]
componentsJoinedByString:@""];
return ([text stringByTrimmingCharactersInSet:nonNumberSet].length > 0);
}
答案 3 :(得分:0)
我最初从这个问题中的一个答案中得到了代码,但是当不允许退格和空格时修改它。以下代码块仅允许使用字母,空格和退格。默认ios键盘中的数字和特殊字符将被忽略。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if ([string isEqualToString:@""]) {
NSString *originalString = textField.text;
NSInteger newLength = [textField.text length];
if (originalString.length > newLength)
myTextfield.text = [originalString substringToIndex:newLength];
return YES;
}
else{
BOOL canEdit=NO;
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"1234567890-/:;()&@\".,?!'[]{}#%^*+=_\\|~<>$£₹€•"];
for (int i = 0; i < [string length]; i++)
{
unichar c = [string characterAtIndex:i];
if ([myCharSet characterIsMember:c])
{
canEdit=NO;
}
else
{
canEdit=YES;
}
}
return canEdit;
}
}