ios - 从 NSString 获取 UILabel 所需的行数?

标签 ios objective-c uitableview nsstring uilabel

如何根据 NSString 中的文本为 UILabel 获取适当的行数?

我需要我的 UITableView 中的一个单元格具有基于 UILabel 高度的动态单元格高度。这意味着我需要根据提供的 NSString 计算出 UILabel 的高度。

最佳答案

您可以使用 UIKit 提供的类别方法返回适合字符串的 CGSize,给定多个不同的输入参数。

据我所知,唯一需要的是指定字体,但您也可以指定其他文本属性。

CGSize size = [text sizeWithAttributes: @{
                  NSFontAttributeName: [UIFont systemFontOfSize:14.0f]
              }];

鉴于此,您可能可以计算出有多少行文本。

请参阅此处的文档: https://developer.apple.com/library/mac/documentation/cocoa/reference/applicationkit/classes/NSString_AppKitAdditions/Reference/Reference.html#//apple_ref/occ/instm/NSString/sizeWithAttributes :

编辑

您可能想看看 boundingRectWithSize:options:attributes: .您将传递标签的大小,string drawing options以及您的文本属性(如字体)。

关于ios - 从 NSString 获取 UILabel 所需的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23035678/

相关文章:

ios - 从 UITableView 中删除行会导致节标题问题吗?

ios - 我如何在 web view iOS swift 中获取 Html 表单值

ios - Core-Plot 选择一个点

ios - 在 UITableView 中加载数据时,cell.contentView.viewWithTag 给出 nil 值

javascript - UIWebView 上的夜间模式问题

ios - 在 iOS 上向 map 添加音频

ios - 在 UITableView 中完成编辑后如何防止单元格宽度扩大

html - iOS 上的列表问题

ios - 围绕屏幕宽度循环字符?

ios - Firebase iOS SDK : How to get multiple Data in one query