getting a NSTextField to grow with the text in auto layout?

后端 未结 5 1465
有刺的猬
有刺的猬 2020-12-05 08:42

I\'m trying to get my NSTextField to have its height grow (much like in iChat or Adium) once the user types enough text to overflow the width of the control (as asked on thi

5条回答
  •  暖寄归人
    2020-12-05 09:08

    The solution by DouglasHeriot only works for fixed width text fields. In my app, I have text fields that I want to grow both horizontally and vertically. Therefore I modified the solution as follows:

    AutosizingTextField.h

    @interface AutosizingTextField : NSTextField {
        BOOL isEditing;
    }
    @end
    

    AutosizingTextField.m

    @implementation AutosizingTextField
    
    - (void)textDidBeginEditing:(NSNotification *)notification
    {
        [super textDidBeginEditing:notification];
        isEditing = YES;
    }
    
    - (void)textDidEndEditing:(NSNotification *)notification
    {
        [super textDidEndEditing:notification];
        isEditing = NO;
    }
    
    - (void)textDidChange:(NSNotification *)notification
    {
        [super textDidChange:notification];
        [self invalidateIntrinsicContentSize];
    }
    
    -(NSSize)intrinsicContentSize
    {
        if(isEditing)
        {
            NSText *fieldEditor = [self.window fieldEditor:NO forObject:self];
            if(fieldEditor)
            {
                NSTextFieldCell *cellCopy = [self.cell copy];
                cellCopy.stringValue = fieldEditor.string;
                return [cellCopy cellSize];
            }
        }
        return [self.cell cellSize];
    }
    @end
    

    There's a minor issue remaining: When typing spaces, the text jumps a bit to the left. However, that's not a problem in my app, because the text fields shouldn't contain spaces in most cases.

提交回复
热议问题