Counting the number of lines in a UITextView, line

2019-01-06 11:51发布

I wanted to know when a text is wrapped by the frame of the text view is there any delimiter with which we can identify whether the text is wrapped or not.

For instance if my text view has a width of 50 px and text is exceeding that, it wraps the text to next line.

I wanted to count the number of lines in my text view. Now "\n" and "\r" are not helping me.

My code is:

NSCharacterSet *aCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"\n\r"];
    NSArray *myArray = [textViewText componentsSeparatedByCharactersInSet:aCharacterSet];
    NSLog(@"%d",[myArray count]);

9条回答
\"骚年 ilove
2楼-- · 2019-01-06 12:49

You need to use the lineHeight property, and font lineHeight:

Objective-C

int numLines = txtview.contentSize.height / txtview.font.lineHeight;

Swift

let numLines = (txtview.contentSize.height / txtview.font.lineHeight) as? Int

I am getting correct number of lines, hope it help you also.

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-06 12:51

I found the perfect solution to this problem in Apple's Text Layout Programming Guide. Here is the solution Apple provides:

NSLayoutManager *layoutManager = [textView layoutManager];
unsigned numberOfLines, index;
unsigned numberOfGlyphs = [layoutManager numberOfGlyphs];
NSRange lineRange;

for (numberOfLines = 0, index = 0; index < numberOfGlyphs; numberOfLines++){
    (void) [layoutManager lineFragmentRectForGlyphAtIndex:index effectiveRange:&lineRange];
    index = NSMaxRange(lineRange);
}

This could easily be written into an extension for UITextView, or as a standalone method taking in a UITextView object as a parameter

查看更多
Melony?
4楼-- · 2019-01-06 12:54

Use this (where _text_v is your text view):

-(NSInteger) linesCount {
    return _text_v.contentSize.height/_text_v.font.lineHeight;
}
查看更多
登录 后发表回答