I have a UITextField
that users will be entering characters into. It is as simple as, how can I return it's actual length? When the string contains A-Z 1-9 characters it works as expected but any emoji or special characters get double counted.
In it's simplest format, this just has an allocation of 2 characters for some special characters like emoji:
NSLog(@"Field '%@' contains %i chars", myTextBox.text, [myTextBox.text length] );
I have tried looping through each character using characterAtIndex
, substringFromIndex
, etc. and got nowhere.
As per answer below, exact code used to count characters (hope this is the right approach but it works..):
NSString *sString = txtBox.text;
__block int length = 0;
[sString enumerateSubstringsInRange:NSMakeRange(0, [sString length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
length++;
}];
NSLog(@"Total: %u", length );
The [myTextBox.text length]
returns the count of unichars and not the visible length of the string. é = e+´
which is 2 unichars. The Emoji characters should contain more the 1 unichar.
This sample below enumerates through each character block in the string. Which means if you log the range of substringRange
it can longer than 1.
__block NSInteger length = 0;
[string enumerateSubstringsInRange:range
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
length++;
}];
You should go and watch the Session 128 - Advance Text Processing from 2011 WWDC. They explain why it is like that. It's really great!
I hope this was to any help.
Cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With