How can I count UITextView characters?

how can I find out the total number of characters that a UITextView shows in its specific contentSize after applying UILineBreakModeWordWrap.

I will use different lines every time as a UITextView text. Lines are much longer than a UITextView specifying the specified area. Visible characters will differ for each line due to the different length of the spaces at the end of the lines.

And I want to know the number of characters visible in my UITextView.

+4
source share
1 answer

Use this method from NSString:

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode 
  • First, you calculate how long the height of the UITextView should fit the entire text.
  • Using proportions, you will find out how long your string should match the actual size.
  • a) If this line matches the current size, you can add characters one by one and check the size again until it no longer fits → the limit is what you are looking for.
  • b) If this line does not match the current size, you delete characters from it one by one until it is set again →, this limit is what you are looking for in this case.

This is a very intensive method, but I think that it is the only one (you can optimize it by adding / removing half of the remaining line instead of adding / removing characters).

+1
source

All Articles