简体   繁体   中英

Not editable NSTextfiled, to make it auto resize when string is too long, like english word to French

As my question being posted, in my textfield, when I open my app in English, it works well, but when switching to French, we know French word is quite long sometimes and in that case, words showing in the textfield will be cut off.

I tried some customised way for textfield on stack overflow, but it works well for editable textfield, when I made it none-editable, the behaviour will be wired.

It's like when the word is too long, it just make textfield longer, meaning just increase width, not height. What I'm expecting is keeping width fix while changing height when word is too long.

intrinsicSize = [super intrinsicContentSize];
NSTextView *textView = (NSTextView *)fieldEditor;
         NSRect usedRect = [textView.textContainer.layoutManager usedRectForTextContainer:textView.textContainer];

kind of two main func I used, when it's editable, everything went well and height changes while width fix, but when it's none editable, only width changes.

Any advice?

In your NSTextField subclass override following methods. Also make sure that NSTextField is set to wrap in IB. Add constraints to it.

 -(NSSize)intrinsicContentSize
{
    // If wrap is not enabled return the original size
    if ( ![self.cell wraps] ) {
    return [super intrinsicContentSize];

    NSRect frame = [self frame];
    CGFloat width = frame.size.width;
    // This will allow to grow it in height and not width
    frame.size.height = CGFLOAT_MAX;
    CGFloat height = [self.cell cellSizeForBounds: frame].height;
    // return the calculated height
    return NSMakeSize(width, height);
}

// Listen to text change notification and invalidate the default size
- (void)textDidChange:(NSNotification *)notification
{
    [super textDidChange:notification];
    [self invalidateIntrinsicContentSize];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM