如何findUITextView的行数

我必须find一个UITextView的行数。 在UITextView上没有可用的属性,比如numberOfLines 。 我使用下面的公式,但它不行。 有人有这个想法吗?

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

如果您使用的是iOS 3,则需要使用leading属性:

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

如果您使用iOS 4,则需要使用lineHeight属性:

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

而且@thomas指出,如果你需要一个确切的结果,要小心四舍五入。

您可以查看UITextView的contentSize属性,以像素为单位获取文本高度,然后除以UITextView字体的行间距,以获得总UIScrollView(在屏幕上和屏幕上)的文本行数,包括两个包裹和行破碎的文本。

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

Swift 4方法来计算使用UITextInputTokenizer UITextView的行数:

 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 } }