2010-04-16 51 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]; 
相關問題