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

标签 ios objective-c nsstring

我正在使用 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/

相关文章:

ios - 检测 UIView 上的触摸

ios - UIScrollViews subview 没有在纵向到横向方向更改上调整自己的大小

objective-c - 如果 json 值 == NULL,RESTKIT 内部映射失败

iphone - 如何在 objective-c 中创建自定义类集群 ..?

iphone - 格式化浮点值

objective-c - 有没有一种简单的方法可以将 NSString 拆分为字符数组?

IOS DidReceiveRemoteNotification 问题

ios - SBJson iOS 解析器方法已弃用?

objective-c - 圆圈叠加跟随用户位置

ios - 使用 NSUTF8StringEncoding 将 NSData 转换为 NSString 对于特殊字符不起作用