1

我正在尝试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
}

基本上,宽度是表格视图的大小减去滚动条和用于显示其他信息的每个单元格的一点点。只要文本比例 (via convertSliderValueToFontScale:) 为 1.0,此方法就非常有效。但是,如果我更改比例因子,则结果usedRectForTextContainer不正确 - 好像没有考虑比例因子。

比例setScaleFactor:forTextView:在 NSTextView 上设置如下(标量是实际的比例量):

[textView scaleUnitSquareToSize:NSMakeSize(scaler, scaler)];

有想法该怎么解决这个吗?

编辑:我有一个示例项目可以在这里尝试:Github。奇怪的是,如果比例 < 0,事情就会起作用,而且它们有时似乎随机地在 4.XXX 范围内工作......

4

1 回答 1

0

答案很简单:将 添加为与 具有相同框架NSTextView的子视图。NSClipViewNSTextView

最终的高度函数如下:

-(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;
}
于 2016-08-25T13:43:10.093 回答