Search code examples
objective-ccocoasizenstextfieldnsfont

Change NSTextField's height according to Font/Size


Ok, here's my situation :

  • I've got an NSTextField, set up as Multi-line Text Label
  • The NSTextField is supposed to be holding just ONE line of text (even if it's a multi-line one)
  • The NSTextField has a fixed height.
  • The Font and Font Size are changed by the user

The issue :

  • Depending on the font used, and size, the bottom part of the text goes missing (as it goes beyond the NSTextField's boundaries

What I want :

  • Get the Text height, based on selection (Font & Font Size) and set the NSTextField's height accordingly.

I know it may sound complicated, but I also know it CAN be done.

Any ideas? Any reference to point me to?


Solution

  • You can take the size of the string and then change the height accordingly

    NSString *text = // your string
    CGSize constraint = CGSizeMake(210, 20000.0f);
    CGSize size = [text sizeWithFont:[UIFont fontWithName:@"Helvetica-Light" size:14] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    
    UITextField *cellTextLabel = [[UITextField alloc] initWithFrame:CGRectMake(70, 9, 230, size.height)];
    cellTextLabel.lineBreakMode = UILineBreakModeWordWrap;
    cellTextLabel.numberOfLines = 50;
    cellTextLabel.backgroundColor = [UIColor clearColor];
    cellTextLabel.text = text;
    cellTextLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:14];
    [self.view addSubview:cellTextLabel];
    [cellTextLabel release];