How to Read Number of lines in UITextView

前端 未结 4 2094
野性不改
野性不改 2020-12-14 16:57

I am using UITextView In my View , I have requirement to count number of line contained by textview am using following function to read \'\\n\' . H

相关标签:
4条回答
  • 2020-12-14 17:20

    You can look at the contentSize property of your UITextView to get the height of the text in pixels, and divide by the line height spacing of the UITextView's font to get the number of text lines in the total UIScrollView (on and off screen), including both wrapped and line broken text.

    0 讨论(0)
  • 2020-12-14 17:33
    extension NSLayoutManager {
        var numberOfLines: Int {
            guard let textStorage = textStorage else { return 0 }
    
            var count = 0
            enumerateLineFragments(forGlyphRange: NSMakeRange(0, numberOfGlyphs)) { _, _, _, _, _ in
                count += 1
            }
            return count
        }
    }
    

    Get number of lines in textView:

    let numberOfLines = textView.layoutManager.numberOfLines
    
    0 讨论(0)
  • 2020-12-14 17:37

    Just for reference...

    Another way you can get the number of lines and also the content, is splitting the lines in an array using the same method mentioned on the answer edit by BoltClock.

    NSArray *rows = [textView.text componentsSeparatedByString:@"\n"];
    

    You can iterate through the array to get the content of each line and you can use the [rows count] to get the exact number of rows.

    One thing to keep in mind is that empty lines will be counted as well.

    0 讨论(0)
  • 2020-12-14 17:42

    In iOS 7, it should exactly be:

    float rows = (textView.contentSize.height - textView.textContainerInset.top - textView.textContainerInset.bottom) / textView.font.lineHeight;
    
    0 讨论(0)
提交回复
热议问题