如何找到UITextView的行数

7

我需要找到一个 UITextView 的行数,但是它没有像 numberOfLines 这样的属性可用。我使用了以下公式,但并没有起作用。是否有任何想法?

int numLines = txtview.contentSize.height/txtview.font.lineHeight;
3个回答

20

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

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

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

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

正如 @thomas 指出的那样,如果您需要精确结果,请注意四舍五入。


1
此外:该公式生成一个浮点值,然后转换为整数(结果为下限)。也许将结果四舍五入会得到更好的结果:int numLines = round(...),这样0.9999的结果就是1而不是0。 - thomas
@thomas:没错。我已经把这个加到答案里了。 - Evan Mulawski

3

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

无法编译“类型'ComparisonResult'的值没有成员'same'”。是某个私有扩展吗? - Pahnev

1
你可以查看UITextView的contentSize属性以获取文本的像素高度,并将其除以UITextView字体的行间距,以获取总UIScrollView中文本行数(包括屏幕内外的所有内容),包括换行和断行文本。
int numLines = txtview.contentSize.height/txtview.font.leading;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接