我需要找到一个 UITextView
的行数,但是它没有像 numberOfLines
这样的属性可用。我使用了以下公式,但并没有起作用。是否有任何想法?
int numLines = txtview.contentSize.height/txtview.font.lineHeight;
我需要找到一个 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 指出的那样,如果您需要精确结果,请注意四舍五入。
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
}
}
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
}
}
}
int numLines = txtview.contentSize.height/txtview.font.leading;
int numLines = round(...)
,这样0.9999的结果就是1而不是0。 - thomas