2010-04-16 133 views
13

我想在NSTextView中设置一个属性字符串。我想根据其内容增加其高度,最初它被设置为某个默认值。如何根据其内容调整NSTextView的大小?

所以这个方法我试过:

我NSTextView设置内容。当我们在NSTextView中设置一些内容时,它的大小会自动增加。所以我增加了它的超级视图的高度,即NSScrollView的高度,但NSScrollView没有得到完全调整大小,它正在显示滚动条。

float xCoordinate = 15.0; 

[xContentViewScroller setFrame:NSMakeRect(xCoordinate, 0.0, 560.0, 10.0)]; 

[[xContentView textStorage] setAttributedString:xContents]; 

float xContentViewScrollerHeight = [xfContentView frame].size.height + 2; 

[xContentViewScroller setFrame:NSMakeRect(xCoordinate, 0.0, 560.0, xContentViewScrollerHeight)]; 

任何人都可以建议我一些方法或方法来解决这个问题。通过这样做谷歌搜索我发现,在UITextView中有contentSize方法,可以得到它的内容的大小,我试图找到类似的方法在NSTextView,但不能得到任何成功:(

+0

解由Peter建议阐述[这里](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/TextLayout/Tasks/StringHeight.html )干杯 – Devarshi 2010-11-22 07:23:39

回答

15
+0

@Peter Hosey - 你能更详细地解释一下吗?我从layoutmanager得到了rect ..现在我应该怎么做才能增加NSTextView的高度? – Saurabh 2011-07-18 09:41:33

+0

@Saurabh:通过文本视图的当前大小之间的差异(或者当它处于一个文本视图的当前大小时),增加文本视图的大小或包含它的滚动视图,滚动视图的父视图或窗口本身的大小滚动视图,当前可见矩形的大小)以及文本实际占用的大小。 – 2011-07-18 10:18:19

+0

@PeterHosey链接已死亡 – Cfr 2017-03-04 00:42:21

2
NSTextView *textView = [[NSTextView alloc] init]; 
textView.font = [NSFont systemFontOfSize:[NSFont systemFontSize]]; 
textView.string = @"Lorem ipsum"; 

[textView.layoutManager ensureLayoutForTextContainer:textView.textContainer]; 

textView.frame = [textView.layoutManager usedRectForTextContainer:textView.textContainer]; 
0
+ (float)heightForString:(NSString *)myString font:(NSFont *)myFont andWidth:(float)myWidth andPadding:(float)padding { 
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:myString]; 
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithContainerSize:NSMakeSize(myWidth, FLT_MAX)]; 
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init]; 
    [layoutManager addTextContainer:textContainer]; 
    [textStorage addLayoutManager:layoutManager]; 
    [textStorage addAttribute:NSFontAttributeName value:myFont 
        range:NSMakeRange(0, textStorage.length)]; 
    textContainer.lineFragmentPadding = padding; 

    (void) [layoutManager glyphRangeForTextContainer:textContainer]; 
    return [layoutManager usedRectForTextContainer:textContainer].size.height; 
} 

我没有使用这个参考值的功能:。Documentation

实施例:

float width = textView.frame.size.width - 2 * textView.textContainerInset.width; 
float proposedHeight = [Utils heightForString:textView.string font:textView.font andWidth:width 
            andPadding:textView.textContainer.lineFragmentPadding]; 
相关问题