简体   繁体   中英

How to find UITextView number of lines

I have to find the number of lines of a UITextView . There is no property available, like a numberOfLines , on UITextView . I use the following formula, but it not doesn't work. Does anybody have an idea about this?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM