UITextField: longitud máxima de caracteres con emoji

Currently I'm using this approach

(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
     NSUInteger newLength = [textField.text length] + [string length] - range.length;
     if(newLength <= 25) {
         self.charsLeft.text = [NSString stringWithFormat:@"%d", 25 - newLength];
     return (newLength > 25) ? NO : YES;

sin que importe charsLeft is label showed in user interface.

Problem came out with emoji. If user enter emoji symbol and then delete it, newLength is going to be equal to 1. So user will see that he have only 24 chars left.

I do know that emoji symbols is surrogate pairs, but I don't understand why if you deleting it than range.length in

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

will be equals 1 and not 2.

How I could fix wrong number in user interface? What am i missing?

preguntado el 23 de abril de 13 a las 14:04

1 Respuestas

I also encountered this problem, I found below two solutions to fix this problem try

- (void)textViewDidChange:(UITextView *)textView
    numberWordLabel.text = [NSString stringWithFormat:@"%d/25",textView.text.length];


use the NSNotificationCenter (from ¿Funciona la observación de valores clave en la propiedad de texto de UITextView?)

- (id)init
    [super init];
    if (self)
        NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
        [nc addObserver:self 
    return self;

- (void)dealloc 
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc removeObserver:self];

- (void)textDidChange:(NSNotification *)note

contestado el 23 de mayo de 17 a las 12:05

Thank you. Second solution is what I was looking for. UITextFieldDelegate no tengo didChange method so first fix is not suitable for me. I still thinking that this problem is bug in SDK =) - thoughtf00l

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.