NSString boundingRectWithSize slightly underestimating the correct height - why?

前端 未结 4 1043
时光说笑
时光说笑 2020-12-16 14:49

I\'m attempting to resize a text field / view automatically depending on its current width. In other words I want the width to stay constant but resize the height according

4条回答
  •  清歌不尽
    2020-12-16 15:25

    This is what I ended up going with (at least for the time being) it seems to work fine, however I still feel like there is a better way to accomplish this.

    NSString *temp = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer vel felis nec massa ultricies blandit non id arcu. Sed enim est. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer vel felis nec massa ultricies blandit non id arcu. Sed enim est.";
    
    myText.stringValue = temp;
    
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                [NSFont systemFontOfSize:12], NSFontAttributeName,
                                [NSParagraphStyle defaultParagraphStyle], NSParagraphStyleAttributeName,
                                nil];
    
    NSSize size = NSMakeSize(window.frame.size.width, MAXFLOAT);
    
    
    myText.frame = [temp boundingRectWithSize:size options:NSLineBreakByWordWrapping | NSStringDrawingUsesLineFragmentOrigin attributes:attributes];
    
    // Keep current width but add some more on the bottom
    NSSize tF = myText.frame.size;
    [myText setFrameSize:NSMakeSize(tF.width, tF.height + 35)];
    
    [myText setFrameOrigin:NSMakePoint((NSWidth(window.frame) - NSWidth(myText.frame)) / 2, 
                                       (NSHeight(window.frame) -  NSHeight(myText.frame) - 20))];
    
    [myText setAutoresizingMask:NSViewMinXMargin | NSViewMaxXMargin | NSViewMinYMargin | NSViewMaxYMargin];
    

    Produces this:

    enter image description here

提交回复
热议问题