How to find a UITextView row count

I need to find the number of rows a UITextView . There is no property, such as numberOfLines , on a UITextView . I use the following formula, but it does not work. Does anyone have an idea about this?

 int numLines = txtview.contentSize.height/txtview.font.lineHeight; 
+6
ios objective-c iphone
source share
3 answers

If you are using iOS 3, you need to use the leading property:

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

If you are using iOS 4, you need to use the lineHeight property:

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

And, as @thomas noted, be careful when rounding if you need an accurate result.

+19
source share

You can look at the contentSize property of your UITextView to get the height of the text in pixels, and divide the distance between the lines of the UITextView font to get the number of text lines in the overall UIScrollView (on and off the screen), including wrapped and broken text.

 int numLines = txtview.contentSize.height/txtview.font.leading; 
+1
source share

Swift 4 way to calculate the number of rows in a UITextView using a UITextInputTokenizer :

 public extension UITextView { /// number of lines based on entered text public var numberOfLines: Int { guard compare(beginningOfDocument, to: endOfDocument).same == false else { return 0 } let direction: UITextDirection = UITextStorageDirection.forward.rawValue var lineBeginning = beginningOfDocument var lines = 0 while true { lines += 1 guard let lineEnd = tokenizer.position(from: lineBeginning, toBoundary: .line, inDirection: direction) else { fatalError() } guard compare(lineEnd, to: endOfDocument).same == false else { break } guard let newLineBeginning = tokenizer.position(from: lineEnd, toBoundary: .character, inDirection: direction) else { fatalError() } guard compare(newLineBeginning, to: endOfDocument).same == false else { return lines + 1 } lineBeginning = newLineBeginning } return lines } } public extension ComparisonResult { public var ascending: Bool { switch self { case .orderedAscending: return true default: return false } } public var descending: Bool { switch self { case .orderedDescending: return true default: return false } } public var same: Bool { switch self { case .orderedSame: return true default: return false } } } 
+1
source share

All Articles