Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save HarrisHan/65d6a93fb9838e582c202e133305f8ec to your computer and use it in GitHub Desktop.
Save HarrisHan/65d6a93fb9838e582c202e133305f8ec to your computer and use it in GitHub Desktop.
limit textField textView input char length
+ (NSUInteger)countLengthOfString:(NSString *)textString {
NSUInteger strlength = 0;
char *p = (char *)[textString cStringUsingEncoding:NSUnicodeStringEncoding];
for (int i = 0; i < [textString lengthOfBytesUsingEncoding:NSUnicodeStringEncoding]; i++) {
if (*p) {
p++;
strlength++;
} else {
p++;
}
}
return strlength;
}
// limit textField's char length
UITextRange *rangeOfMarked = [textField markedTextRange];
if (!rangeOfMarked) {
if ([NSString countLengthOfString:textField.text] > LIMIT_CHARACTOR) {
NSString* tmp;
for (NSInteger i = textField.text.length; i > 0; i--) {
tmp = [textField.text substringToIndex:i];
if ([NSString countLengthOfString:tmp] <= LIMIT_CHARACTOR) {
textField.text = tmp;
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment