简体   繁体   English

如何将NSTextView字符串中的字体调整为NSTextView大小

[英]How to have font in NSTextView string adjust to NSTextView size

How do I have the text of an NSTextView adjust to fit the contents of the box without having to need to scroll? 如何在不滚动的情况下调整NSTextView的文本以适合框的内容? For instance, if the user typed in a long string and if I later display the string back as an NSTextView, how can I make it so that the font decreases to a small enough size to fit the box? 例如,如果用户键入了一个长字符串,并且以后又将其显示为NSTextView,那么如何使字体减小到足够小以适合框的大小呢?

In this question , the accepted answer provides a way to measure the height of text in an NSTextView. 这个问题中 ,被接受的答案提供了一种测量NSTextView中文本高度的方法。 Using that, you could cycle through different font sizes (ie from 8-18) from largest to smallest stopping & selecting the first one which fits the NSTextView height. 使用该功能,您可以从最大到最小停顿循环选择不同的字体大小(即从8到18)并选择适合NSTextView高度的第一个。

(totally untested) code: (未经测试)代码:

- (void)autoAdjustFontSizeForTextView:(NSTextView *)myView
{
    int minFont = 8;
    int maxFont = 18;

    for (int i=maxFont; i>=minFont; i--)
    {
      NSFont *myFont = [NSFont fontWithName:@"Lucida Grande" size:i];
        int textHeight = [self heightOfStringInTextView:myView withFont:myFont];
        if (textHeight < [myView frame].size.height)
        {
            // set view font
            [textView setFont:myFont];
            return;
        }
    }
}

- (int)heightOfStringInTextView:(NSTextView *)myView withFont:(NSFont *)myFont
{
    NSDictionary *attributes
      = [NSDictionary dictionaryWithObjectsAndKeys:
         myFont,NSFontAttributeName,nil];
    NSAttributedString *attributedString
      = [[NSAttributedString alloc] initWithString:
         [myView string] attributes:attributes];
    CGFloat height = [attributedString heightForWidth:
                     [myView frame].size.width];
    return (int)height;
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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