Lloyd Hendricks
Lloyd Hendricks

Reputation: 11

Swift 3 - UITextView total line counter

Good day all hope your well.

This possibly seems like a repeat question but nothing is working for me.

I have looked at multiple instances of this question and I have tried many different things and it doesn't solve my problem.

I have a textview that is constrained to 11 Lines and then becomes scrollable..... I want to get the total line count of the text content not the display size on the screen all the solutions just provide me with 11 lines but the true line count is +- 30 lines.Even if I show 5 Lines of text it returns 11

How can i find out the line count of all the text collectivly.

Any help would be much appreciated

Upvotes: 0

Views: 1449

Answers (2)

Nikolay Khramchenko
Nikolay Khramchenko

Reputation: 421

Use this extension for solve your problem!

extension String {
    func lines(font : UIFont, width : CGFloat) -> Int {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude);
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil);
        return Int(boundingBox.height/font.lineHeight);
    }
}

Upvotes: 1

Agent Smith
Agent Smith

Reputation: 2923

Here what I'm doing

 extension String {
        func lines() -> CGFloat {

        let font = //your font
        let width = //constrained width to which text can expand
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

        return boundingBox.height/font.lineHeight
        } 
 }

This will give you the number of Lines that are actually a string is taking.

Hope it helps!!

Upvotes: 0

Related Questions