我在我的应用程序中使用文本字段,我想限制用户在文本字段中仅输入 15 个字符。之后,他/她将无法在文本字段中输入内容。
我该如何设置这种功能?
//它的代码很大,但对我来说工作正常
//在此代码中输入您的文本字段名称而不是 YourTextFieldName
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField==YourTextFieldName)
{
NSString *text = nil;
int MAX_LENGTH = 12;
text = YourTextFieldName.text;
if ([text length] <= 7)
{
NSString *separator = @"-";
int seperatorInterval = 3;
NSString *originalString = [textField.text stringByReplacingOccurrencesOfString:separator withString:@""];
if (![originalString isEqualToString:@""] && ![string isEqualToString:@""])
{
NSString *lastChar = [YourTextFieldName.text substringFromIndex:[YourTextFileName.text length] - 1];
int modulus = [originalString length] % seperatorInterval;
if (![lastChar isEqualToString:separator] && modulus == 0)
{
YourTextFieldName.text = [YourTextFieldName.text stringByAppendingString:separator];
}
}
}
if ([text length] > 7)
{
NSString *separator = @"-";
int seperatorInterval = 6;
NSString *originalString = [textField.text stringByReplacingOccurrencesOfString:separator withString:@""];
if (![originalString isEqualToString:@""] && ![string isEqualToString:@""])
{
NSString *lastChar = [YourTextFieldName.text substringFromIndex:[YourTextFieldName.text length] - 1];
int modulus = [originalString length] % seperatorInterval;
if (![lastChar isEqualToString:separator] && modulus == 0)
{
YourTextFieldName.text = [YourTextFieldName.text stringByAppendingString:separator];
}
}
}
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > MAX_LENGTH) ? NO : YES;
}
return YES;
}
这有一点技巧,您需要先计算新字符串是什么,然后才能测试是否允许或拒绝更改
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if ([newString length] > 15) {
return FALSE;
} else {
return TRUE;
}
}
使用方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (([textField.text length] - range.length) == 15) {
return NO;
}
return YES;
}
希望能帮助到你。快乐编码:)
您可以检查是否输入和计数字符
(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (range.length > 15) {
// delete
}
else
{
// add
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.text.length >= 15)
{
return NO; //return NO to not change text
}
return YES;
}