Search code examples
objective-ccocoanstextfieldnsmutableattributedstring

how to make NSTextField to fit NSMutableAttributedString contained


I have a NSTextField where I add NSMutableAttributedString. I want to set the size of that string to big number, however when I do that the text appears cut off. How can tell the NSTextField to get bigger?

This is what I have:

NSTextField* textField = [[NSTextField alloc] init];
NSMutableAttributedString* text = [[NSMutableAttributedString alloc]
  initWithString:@"0"];
NSRange titleRange = NSMakeRange(0, [text length]);
[text addAttribute:NSFontAttributeName
           value:[NSFont boldSystemFontOfSize:25]
           range:titleRange];
[textField setAttributedStringValue:text];

Any advice? Thanks in advance


Solution

  • Make a subclass of NSTextField

    In implementation do override intrinsicContentSize

    -(NSSize)intrinsicContentSize
    {
        if ( ![self.cell wraps] ) {
            return [super intrinsicContentSize];
        }
    
        NSRect frame = [self frame];
    
        CGFloat width = frame.size.width;
    
        frame.size.height = CGFLOAT_MAX;
    
        CGFloat height = [self.cell cellSizeForBounds: frame].height;
    
        return NSMakeSize(width, height);
    }
    
    // Than invalidate the layout when text changes
    - (void)textDidChange:(NSNotification *)notification
    {
        [super textDidChange:notification];
        [self invalidateIntrinsicContentSize];
    }
    

    In attribute Inspector inside storyboard set NSTextField class to your customNSTextField class and change layout to wraps from scrolls. You must add constraints to your textField to its superview, easier in storyboard.

    After that you can also set font size directly :

    [_textField setFont:[NSFont systemFontOfSize:25]];