首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSLayoutManager/NSTextContainer忽略比例因子

NSLayoutManager/NSTextContainer忽略比例因子
EN

Stack Overflow用户
提问于 2016-08-23 03:59:38
回答 1查看 360关注 0票数 1

我正在尝试使用以下方法测量给定恒定宽度的NSAttributedString的高度:

代码语言:javascript
复制
-(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,这种方法就能很好地工作。但是,如果我更改比例因子,则usedRectForTextContainer的结果是不正确的--就好像没有考虑比例因子一样。

在NSTextView上的setScaleFactor:forTextView:中按如下方式设置比例(标量是实际缩放量):

代码语言:javascript
复制
[textView scaleUnitSquareToSize:NSMakeSize(scaler, scaler)];

有什么办法解决这个问题吗?

编辑:我在这里有一个样例项目可以尝试:Github。奇怪的是,如果规模小于0,事情就会正常工作,有时它们似乎随机地在4.XXX范围内工作……

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-25 21:43:10

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

最终的高度函数如下:

代码语言:javascript
复制
-(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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39087754

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档