• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

[复制链接]
菜鸟教程小白 发表于 2022-12-12 10:41:14 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

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

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap