OGeek|极客世界-中国程序员成长平台

标题: ios - sizeWithAttributes 返回带有新行字符的错误大小\n [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 10:41
标题: ios - sizeWithAttributes 返回带有新行字符的错误大小\n

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

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

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

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



Best Answer-推荐答案


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

您需要使用 boundingRectWithSizeptions: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/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4