在文本字段中放置范围并避免特殊字符
Put range and avoid special character in a textfield
我正在研究 iOS。我有一个文本字段,它的范围应该是 7 位数字,并且还要避免使用特殊字符。我只想输入 0-9999999 之间的数字。请帮助
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(range.length + range.location > textField.text.length)
{
return NO;
}
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return newLength <= 7;
}
在您的文本字段委托方法中 shouldChangeCharactersInRange
这将只允许 0-9 数字,不允许字母,也不允许特殊字符
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *aCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
for (int i = 0; i < [string length]; i++) {
unichar aCharacter = [string characterAtIndex:i];
if (![aCharacterSet characterIsMember:aCharacter]) {
return NO;
}
return YES;
}
}
使用这个
#define acceptableCharacterSet @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:acceptableCharacterSet] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
if(![string isEqualToString:filtered])
return NO;
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 7) ? NO : YES;
}
我正在研究 iOS。我有一个文本字段,它的范围应该是 7 位数字,并且还要避免使用特殊字符。我只想输入 0-9999999 之间的数字。请帮助
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(range.length + range.location > textField.text.length)
{
return NO;
}
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return newLength <= 7;
}
在您的文本字段委托方法中 shouldChangeCharactersInRange
这将只允许 0-9 数字,不允许字母,也不允许特殊字符
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *aCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
for (int i = 0; i < [string length]; i++) {
unichar aCharacter = [string characterAtIndex:i];
if (![aCharacterSet characterIsMember:aCharacter]) {
return NO;
}
return YES;
}
}
使用这个
#define acceptableCharacterSet @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:acceptableCharacterSet] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
if(![string isEqualToString:filtered])
return NO;
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 7) ? NO : YES;
}