1

ユーザーの入力を既に変更している iOS アプリに UITextField があります。UITextField が一定数の文字を保持できることも確認する必要があることに気付きました。私は次のようにデリゲートメソッドを実装しています:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    if([[string stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]]
        isEqualToString:@""])
        return YES;

    NSString *previousValue = [[[textField.text stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] stringByReplacingOccurrencesOfString:@"." withString:@""] stringByReplacingOccurrencesOfString:@"," withString:@""];
    string = [string stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
    NSString *modifiedValue = [NSString stringWithFormat:@"%@%@", previousValue, string];

    if ([modifiedValue length] == 1) {

        modifiedValue = [NSString stringWithFormat:@"0.0%@", string];

    }

    else if ([modifiedValue length] == 2) {

        modifiedValue = [NSString stringWithFormat:@"0.%@%@", previousValue, string];

    }

    else if ([modifiedValue length] > 2) {

        modifiedValue = [NSString stringWithFormat:@"%@.%@",[modifiedValue substringToIndex: modifiedValue.length-2],[modifiedValue substringFromIndex:modifiedValue.length-2]];

    }


    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSDecimalNumber *decimal = [NSDecimalNumber decimalNumberWithString:modifiedValue];
    modifiedValue = [formatter stringFromNumber:decimal];
    [textField setText:modifiedValue];

    return NO;

}

上記のコードで、22 文字の制限を考慮に入れる方法がわかりません。誰が私が何をする必要があるかを見ることができますか?

4

4 に答える 4

4

このようにしてみて、

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if([textField.text length]<=22)
   return YES;
else
   return NO;
}

また

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

return (textField.text.length <= 22);
}
于 2013-03-29T09:57:48.890 に答える
0

これを試して:-

 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {


        print("chars \(textField.text!.characters.count) \( string)")

        if(textField.text!.characters.count > 20 && range.length == 0) {
            print("Please summarize in 20 characters or less")
            return false;
        }

        return true;
}
于 2016-08-16T11:13:56.317 に答える