LoginSignup
12
14

More than 5 years have passed since last update.

UITextFieldで入力された文字の判定や、文字数、Byte数を取得する

Last updated at Posted at 2016-01-18

UITextFieldのDelegateメソッドのメモ

.m
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    NSLog(@"入力された文字 : \"%@\"",string);
    NSLog(@"入力済みの文字 : \"%@\"",textField.text);
    NSLog(@"入力完了後の文字 : \"%@\"",newString);
    NSLog(@"入力完了後の文字数 : %ld",(long)[newString length]);
    NSLog(@"入力完了後のByte数 : %ld",(long)[newString lengthOfBytesUsingEncoding:NSShiftJISStringEncoding]);
    NSLog(@"削除キー押下? : %d",[string length] == 0 && range.length > 0);

    return YES;
}

上記の方法だと、日本語入力で変換中の場合、ローマ字(英語)で取得するので("あ"が変換中の場合は"a"を取得)
表示されている文字そのものを取得する場合は下記で。

.m
- (void)viewDidLoad
{
    [super viewDidLoad];

    // 文字入力時に指定のメソッドを呼ぶ
    [_textField addTarget:self action:@selector(didChangeTextField:) forControlEvents:UIControlEventEditingChanged];
}

/**
 *  テキストフィールドの値が変更される度に呼ばれます
 *
 *  @param textField UITextField
 */
- (void)didChangeTextField:(UITextField *)textField
{
    NSString *text = textField.text; // 入力されている文字を取得
}

12
14
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
14