Tuan Anh Vu Tuan Anh Vu - 1 month ago 6
Swift Question

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")

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.



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