gpt4 book ai didi

ios - sizeWithAttributes 返回带有新行字符的错误大小\n

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:58:08 26 4
gpt4 key购买 nike

我正在使用 NSString 的 sizeWithAttributes 方法来获取 NSString 的动态高度。

我的字符串是@"This is address line1\n This is address line2"

但是方法只返回第 1 行的大小(在\n 字符之前)

有什么方法可以在字符串大小中包含\n 吗?

最佳答案

您不能使用 sizeWithAttributes 来计算多行文本的大小。想想看。多行文本的大小取决于必须绘制的宽度。sizeWithAttributes 不允许您指定分配的宽度。

您需要使用 boundingRectWithSize:options:attributes:context:。指定具有所需宽度和非常大的高度的尺寸。返回值将为您提供所需的大小,以将文本换行到指定大小。

它的一个使用示例是:

NSString *addressString = ... // your string to measure
NSDictionary *attributes = @{ NSFontAttributeName : [UIFont fontWithName:kFontName size:kProductFont] };
CGFloat desiredWidth = 300; // adjust accordingly
CGRect neededRect = [addressString
boundingRectWithSize:CGSizeMake(desiredWidth, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:attributes context:nil];
CGFloat neededHeight = neededRect.size.height;

关于ios - sizeWithAttributes 返回带有新行字符的错误大小\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35629217/

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