Search code examples
macoscocoanstextfield

Updating the size of NSTextField with respect to length of the string


I am trying to update the height of the NSTextField w.r.t the length of the string but if the string is light the last portion gets cut off.This is my code.

 self.solutionTextView.frame = CGRectMake(self.solutionTextView.frame.origin.x, self.solutionTextView.frame.origin.y, self.solutionTextView.frame.size.width + 25 ,self.solutionTextView.frame.size.height + 25);
//self.solutionTextView.sizeToFit()

What am i doing wrong?


Solution

  • If the NSTextField is allowed to wrap the string, the following steps are the standard (or usual? or one of more possible?) ways to determine the wanted height of the field. Assume the width of the field is given:

    NSRect frame = [textField frame];
    

    Now make it very high:

    NSRect constraintBounds = frame;
    constraintBounds.size.height =  10000.0;
    [textField setFrame: constraintBounds];
    

    and set the string:

    [textField  setStringValue:theString];
    

    Ask now for the natural size:

     NSSize naturalSize =
            [[textField cell] cellSizeForBounds:constraintBounds];
    

    And you are done:

     frame.size = naturalSize;
     [textField setFrame:frame];