こんにちは、ユーザーが数字の文字列を入力して、文字列の5文字ごとにハイフンを動的に追加することが可能かどうか疑問に思っています...
どんな助けでも大歓迎です。
こんにちは、ユーザーが数字の文字列を入力して、文字列の5文字ごとにハイフンを動的に追加することが可能かどうか疑問に思っています...
どんな助けでも大歓迎です。
このコードを試してください。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *separator = @"-";
int seperatorInterval = 5;
NSString *originalString = [textField.text stringByReplacingOccurrencesOfString:separator withString:@""];
if (![originalString isEqualToString:@""] && ![string isEqualToString:@""]) {
NSString *lastChar = [textField.text substringFromIndex:[textField.text length] - 1];
int modulus = [originalString length] % seperatorInterval;
if (![lastChar isEqualToString:separator] && modulus == 0) {
textField.text = [textField.text stringByAppendingString:separator];
}
}
return YES;
}
入力にUITextFieldを使用していると仮定すると、UITextFieldTextDidChangeNotification
アクションを使用して、テキストが変更されるたびに応答できます。簡単で大まかな例:
- (IBAction)textChanged:(UITextField*)sender
{
NSString* curText = sender.text;
//when checking the length, you need to exclude hyphens from the count
//which is currently not being done (thanks @titaniumdecoy)
if([curText length] % 5 == 0)
{
sender.text = [curText stringByAppendingString:@"-"];
}
}
2 つの文字列を宣言して割り当てるだけです。数値を 1 つの文字列 (str 1) に格納し、エントリごとに文字列の長さをカウントします。文字列の長さが 4 桁になるタイミングを確認し、実行します
str2 = [str1 appendByString:@"`"];
今str1 = str2;
このプロセスを 4 桁ずつ増やしてループで繰り返します。
それが役立つことを願っています。
5文字ごとに部分文字列を作成し、これらにハイフンを追加して、それぞれを連結しようとする概念です。このためには、部分文字列の配列を作成する必要があります。この論理関数を使用してください
-(NSString *)makeMyString:(NSString *)stringA
{
NSMutableArray *tempArray1=[NSMutableArray array];
//NSString *s=@"12345123451234512";
NSString *s=stringA;
BOOL flag=YES;
while(flag)
{
NSString *str;
if([s length]>=5)
str=[s substringWithRange:NSMakeRange(0,5)];
else
str=s;
[tempArray1 addObject:str];
str=nil;
if([s length]>=5)
s=[s substringWithRange:NSMakeRange(5,([s length]-5))];
else
s=@"";
if([s isEqualToString:@""])
flag=NO;
}
NSString *makeString=@"";
for(int i=0;i<[tempArray1 count];i++)
{
if([[tempArray1 objectAtIndex:i] length]==5)
makeString =[NSString stringWithFormat:@"%@%@`",makeString,[tempArray1 objectAtIndex:i]];
else {
makeString =[NSString stringWithFormat:@"%@%@",makeString,[tempArray1 objectAtIndex:i]];
}
}
NSLog(@"%@",makeString);
return makeString;
}