gpt4 book ai didi

objective-c - NSString boundingRectWithSize 稍微低估了正确的高度 - 为什么?

转载 作者:太空狗 更新时间:2023-10-30 03:18:52 29 4
gpt4 key购买 nike

我正在尝试根据其当前宽度自动调整文本字段/ View 的大小。换句话说,我希望宽度保持不变,但根据提供给它的文本调整高度。

它似乎工作正常,但出于某种原因,尽管已努力将其移回,但它仍与我的窗口底部对齐。任何人都可以看到我在这里做错了什么吗?

enter image description here

NSString *temp = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer vel felis nec massa ultricies blandit non id arcu. Sed enim est, facilisis a feugiat in, consectetur eget arcu. Aenean rutrum, lacus id euismod congue, nisl erat vulputate lectus, non faucibus tortor purus sed sem. Donec tempor dui egestas velit auctor vitae faucibus diam facilisis. Morbi convallis nulla quis est pulvinar quis ultricies sem sollicitudin.";

myText.stringValue = temp;

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
[NSFont systemFontOfSize:12], NSFontAttributeName,
[NSParagraphStyle defaultParagraphStyle], NSParagraphStyleAttributeName,
nil];

NSSize size = NSMakeSize(window.frame.size.width, 200);
myText.frame = [temp boundingRectWithSize:size options:NSLineBreakByWordWrapping | NSStringDrawingUsesLineFragmentOrigin attributes:attributes];

编辑:即使手动移动框架,很明显文本仍会被截断。新调整的大小不完全存在。 enter image description here

这是引用: NSString boundingRectWithSize slightly underestimating the correct width - why?NSTextView or NSTextField automatically resize bounds / frame?

最佳答案

我遇到了同样的问题。我在 the Documentation 中找到了以下内容:

To correctly draw and size multi-line text, pass NSStringDrawingUsesLineFragmentOrigin in the options parameter.

This method returns fractional sizes (in the size component of the returned CGRect); to use a returned size to size views, you must raise its value to the nearest higher integer using the ceil function.

所以这为我解决了:

CGRect rect = [myLabel.text boundingRectWithSize:CGSizeMake(myLabel.frame.size.width, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName: myLabel.font}
context:nil];
rect.size.width = ceil(rect.size.width);
rect.size.height = ceil(rect.size.height);

更新(Swift 5.1)

另一种 Swift 方法是:

let size = myLabel.text!.size(
withAttributes: [.font: myLabel.font!]
)
let rect = CGSize(
width: ceil(size.width),
height: ceil(size.height)
)

参见 this answer一个 Objective-C 的例子。

关于objective-c - NSString boundingRectWithSize 稍微低估了正确的高度 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12084760/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com