[英]NSLayoutManager/NSTextContainer Ignores Scale Factor
我試圖使用以下方法測量給定恆定寬度的NSAttributedString
的高度:
-(CGFloat)calculateHeightForAttributedString:(NSAttributedString*)attributedNotes {
CGFloat scrollerWidth = [NSScroller scrollerWidthForControlSize:NSRegularControlSize scrollerStyle:NSScrollerStyleLegacy];
CGFloat width = self.tableView.frame.size.width - self.cellNotesWidthConstraint - scrollerWidth;
// http://www.cocoabuilder.com/archive/cocoa/54083-height-of-string-with-fixed-width-and-given-font.html
NSTextView *tv = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, width - 20, 1e7)];
tv.font = [NSFont userFontOfSize:32];
[tv.textStorage setAttributedString:attributedNotes];
[self setScaleFactor:[self convertSliderValueToFontScale:self.fontScaleSlider] forTextView:tv];
[tv.layoutManager glyphRangeForTextContainer:tv.textContainer];
[tv.layoutManager ensureLayoutForTextContainer:tv.textContainer];
return [tv.layoutManager usedRectForTextContainer:tv.textContainer].size.height + 10.0f; // add a little bit of a buffer
}
基本上,寬度是表格視圖的大小減去滾動條,以及用於顯示其他信息的每個單元格的一小部分。 只要文本比例(通過convertSliderValueToFontScale:
為1.0,此方法convertSliderValueToFontScale:
很好地工作。 如果改變比例因子, usedRectForTextContainer
的結果是不正確的 - 好像沒有考慮比例因子。
比例在setScaleFactor:forTextView:
設置setScaleFactor:forTextView:
在NSTextView上如下(標量是實際比例量):
[textView scaleUnitSquareToSize:NSMakeSize(scaler, scaler)];
有想法該怎么解決這個嗎?
編輯:我有一個示例項目在這里嘗試: Github 。 奇怪的是,如果比例小於0,事情就會起作用,並且它們隨機似乎在4.XXX范圍內隨機工作......
答案結果是簡單:添加NSTextView
作為的子視圖NSClipView
具有相同的幀作為NSTextView
。
最終的高度函數如下:
-(CGFloat)calculateHeightForAttributedString:(NSAttributedString*)attributedNotes {
CGFloat width = self.textView.frame.size.width;
// http://www.cocoabuilder.com/archive/cocoa/54083-height-of-string-with-fixed-width-and-given-font.html
NSTextView *tv = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, width, 1e7)];
tv.horizontallyResizable = NO;
tv.font = [NSFont userFontOfSize:32];
tv.alignment = NSTextAlignmentLeft;
[tv.textStorage setAttributedString:attributedNotes];
[self setScaleFactor:self.slider.floatValue forTextView:tv];
// In order for usedRectForTextContainer: to be accurate with a scale, you MUST
// set the NSTextView as a subview of an NSClipView!
NSClipView *clipView = [[NSClipView alloc] initWithFrame:NSMakeRect(0, 0, width, 1e7)];
[clipView addSubview:tv];
[tv.layoutManager glyphRangeForTextContainer:tv.textContainer];
[tv.layoutManager ensureLayoutForTextContainer:tv.textContainer];
return [tv.layoutManager usedRectForTextContainer:tv.textContainer].size.height;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.