I have to find the number of lines of a UITextView
. There is no property available, like anumberOfLines
, on UITextView
. I use the f
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 pointed out, be careful of rounding if you need an exact result.
Swift 4 way to calculate number of lines in UITextView
using 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
}
}
}
You can look at the contentSize property of your UITextView to get the height of the text in pixels, and divide by the line 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.
int numLines = txtview.contentSize.height/txtview.font.leading;