我在NSTextView
内部NSView
(由NSPopover
使用,不知道是否相关)我正在尝试自动调整大小(参见标题)。
我一直在努力解决很多问题,即:
NSLayoutManager
和usedRectForTextContainer
(usedRectForTextContainer : {{0, 0}, {0.001, 28}}
)NSScrollView frame
,[NSScrollView contentView]
,[NSScrollView documentView]
我达到了可以调整我的scollview和我的Popover大小的程度,但我无法获得NSTextView中文本的实际高度。
任何形式的帮助都将受到赞赏。
-(void)resize
{
//Get clipView and scrollView
NSClipView* clip = [popoverTextView superview];
NSScrollView* scroll = [clip superview];
//First, have an extra long contentSize and ScrollView to test everything else
[popover setContentSize:NSMakeSize([popover contentSize].width, 200)];
[scroll setFrame:(NSRect){
[scroll frame].origin.x,[scroll frame].origin.y,
[scroll frame].size.width,155
}];
NSLayoutManager* layout = [popoverTextView layoutManager];
NSTextContainer* container = [popoverTextView textContainer];
NSRect myRect = [layout usedRectForTextContainer:container]; //Broken
//Now what ?
}
答案 0 :(得分:3)
我仍然不知道为什么我不能使用[layout usedRectForTextContainer:container]
,但我设法通过使用以下方式获得NSTextView
的高度:
-(void)resize
{
//Get glyph range for boundingRectForGlyphRange:
NSRange range = [[myTextView layoutManager] glyphRangeForTextContainer:container];
//Finally get the height
float textViewHeight = [[myTextView layoutManager] boundingRectForGlyphRange:range
inTextContainer:container].size.height;
}
答案 1 :(得分:2)
这是我为swift测试过的一些功能代码。 usedRectForTextContainer没有被破坏它只是懒惰地设置。要设置它,我称之为glyphrangefortextcontainer
我在这里找到答案:http://stpeterandpaul.ca/tiger/documentation/Cocoa/Conceptual/TextLayout/Tasks/StringHeight.html
let textStorage = NSTextStorage(string: newValue as! String)
let textContainer = NSTextContainer(size: NSSize(width: view!.Text.frame.width, height:CGFloat.max))
let layoutManager = NSLayoutManager()
layoutManager.addTextContainer(textContainer)
textStorage.addLayoutManager(layoutManager)
textContainer.lineFragmentPadding = 0.0
textContainer.lineBreakMode = NSLineBreakMode.ByWordWrapping
textStorage.font = NSFont(name: "Times-Roman", size: 12)
layoutManager.glyphRangeForTextContainer(textContainer)
let rect = layoutManager.usedRectForTextContainer(textContainer)
Swift.print(rect)
文档还表明情况就是这样: