Tuan Anh Vu
Tuan Anh Vu

Reputation: 780

Get number of lines UITextView without using "\n"?

I have a textView that I need the number of lines for, or the sizeToFit before it becomes sizeToFit. I've tried checking for number of line breaks "\n" in the textView. However, the text in the textView has been parsed bc it was pretty messy coming from the server with tons of html codes and awful line breaks that I had to use replaceOccurence of "\n" to remove the line breaks to make the text into one nice paragraph.

var rawString = self.selectedProduct.description   
var cleanString = rawString?.stringByReplacingOccurrencesOfString("\n", withString: " ", options: NSStringCompareOptions.LiteralSearch, range: nil)

This code, of course, will only return 1 after the above code.

let desString = self.descriptionTextView.text
let numLines = desString.componentsSeparatedByString("\n")
println(numLines.count)

This code, crashes.

 let numLines = self.descriptionTextView.contentSize.height / self.descriptionTextView.font.leading

Ultimately, what I want to partially show the text and have a button that reveals all the text.

Thanks

Upvotes: 0

Views: 3005

Answers (1)

Arbitur
Arbitur

Reputation: 39081

I have converted @aBilal17's comment to non depreciated stuff and swift.

// This gives you the size of that string

let font = UIFont.systemFontOfSize(11)
let style = NSMutableParagraphStyle()
style.lineBreakMode = NSLineBreakMode.ByWordWrapping
let size = someString.sizeWithAttributes([NSFontAttributeName: font, NSParagraphStyleAttributeName: style])

I use this extension I made to get the size of a string restrained to width:

extension String {
    func sizeForWidth(width: CGFloat, font: UIFont) -> CGSize {
        let attr = [NSFontAttributeName: font]
        let height = NSString(string: self).boundingRectWithSize(CGSize(width: width, height: CGFloat.max), options:.UsesLineFragmentOrigin, attributes: attr, context: nil).height
        return CGSize(width, ceil(height))
    }
}

So In your case you can do:

let numLines = desString.sizeForWidth(descriptionTextView.contentSize.width, font: descriptionTextView.font).height / descriptionTextView.font.lineHeight

Upvotes: 6

Related Questions