アプリケーションでテキストフィールドを使用していますが、ユーザーがテキストフィールドに入力するのは15文字のみに制限したいと思います。その後、彼/彼女はテキストフィールドに入力できないはずです。
この種の機能を設定するにはどうすればよいですか?
アプリケーションでテキストフィールドを使用していますが、ユーザーがテキストフィールドに入力するのは15文字のみに制限したいと思います。その後、彼/彼女はテキストフィールドに入力できないはずです。
この種の機能を設定するにはどうすればよいですか?
これには少しトリックがあります。変更を許可するか拒否するかをテストする前に、新しい文字列がどうなるかを計算する必要があります。
- (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;
}
}
//その大きなコードですが、私にとってはうまく機能しています
//このコードに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
{
if (range.length > 15) {
// delete
}
else
{
// add
}
}
使用方法
- (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 (textField.text.length >= 15)
{
return NO; //return NO to not change text
}
return YES;
}