Search code examples
macosswiftmultiline

set height of multi line label in OSX


I am trying to set the height of the multiline label in OSX but when i use sizetofit functionality it cuts the line width and doesn't set the height.What i want is to be able to grow multi line label as its size increases automatically setting the height and the width.This is the code i am working on right now.

self.solutionTextView.stringValue = String(format: "asjdasjdhsjf dasfjashd fjadhsf sfsdjfijijij dsfsd jsj aidjfajs jfsajf isdj sjdaofjaisdjf i dsfisdfjsdjfi sj jasof sjdf ijsdj fisjdsj fjas jsid isdf jsdi fsiajf isjfi jdsjf saof jisadfj isjdfisdj foajdfjsdawei difj jhjsahhjashashhjsahsahjhsahjsahjshajhsahsahjhjsahjsahjhjsahsahjsajhjhashjshjhjsahsjahjsahjsahsahjsahjshahsjahjsahjsahjshhsjahjsahjsahjsahjhjsahjsahsahhsahjsahsahhsajhjsahjsahjhsjahjsahjsahjhsjahjahjsahjshjahjsahjhjahjsahjhsjahjshjshajhjsahjsahjshjahjsahjsahjshjahjsahjshjahjsahjsahsahhjsahjsahjsahjsahjhjsahjahjsahhsahjjasjhhjsahjsahhjsahjhjsahjsajhhjsahjhjsahjsahjhjsahjshjahjsahjsahjjhashjshajhahjahjhsahhajshjashahjshhjahj%@", self.recommendation.valueForKey("solution") as String)
self.solutionTextView.sizeToFit()
self.linksTextView.stringValue = String(format: "First Link %@", self.recommendation.valueForKey("tip1") as String)
//    self.linksTextView.sizeToFit()
self.proTipTextView.stringValue = String(format: "Pro Tip: Not available")

Solution

  • I am developing on iOS and although your variable is named 'self.solutionTextView' I assume we are talking about the equivalent of a UILabel. In this case you could measure the text and use this as an frame:

    let frame = self.solutionTextView.frame
    frame.size.height = NSString(string:self.solutionTextView.stringValue).sizeWithAttributes([NSFontAttributeName : self.solutionTextView.font]).height
    self.solutionTextView.frame = frame
    

    I also assume you have a set width and are more interested in scaling the label vertically in height. If not, the method above returns a size which you can use to get the width.