iphone - UILabel 与 UILineBreakModeWordWrap 的结果行

标签 iphone cocoa-touch iphone-sdk-3.0 nsstring uilabel

我有一个 UILabel,其大小是使用 sizeWithFont: 方法计算的。换行模式设置为 UILineBreakModeWordWrap(使用 sizeWithFont: 计算大小时使用相同的标志)...

一切都很好,标签大小合适,并根据需要显示我的文本。

现在我需要知道用于显示标签的行(或使用 sizeWithFont: 时生成的行)。从技术上讲,我可以编写自己的基于空格/插入符返回的换行实现,但是不能保证它与 Apple 的实现方式相同,因此生成的行将不是用于计算文本大小的行,不要介意重新发明轮子的事实。

理想情况下,我会传递字符串,指定宽度和换行模式并接收表示文本可视行的字符串数组。

有什么想法可以以最优雅的方式实现这一点吗?

最佳答案

要计算 UILabel 文本换行后的行数,您需要找到 UILabel 字体的前导(行高)(label.font.leading),然后将多行 UILabel 的高度除以每行的高度即可得出行数。

这是一个例子:

- (void)viewDidLoad {

    [super viewDidLoad];

    UILabel *label = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
    label.numberOfLines = 0;
    label.lineBreakMode = UILineBreakModeWordWrap;  
    label.text = @"Some really really long string that will cause the label's text to wrap and wrap and wrap around. Some really really long string that will cause the label's text to wrap and wrap and wrap around.";

    CGRect frame = label.frame;
    frame.size.width = 150.0f;
    frame.size = [label sizeThatFits:frame.size];
    label.frame = frame;

    CGFloat lineHeight = label.font.leading;
    NSUInteger linesInLabel = floor(frame.size.height/lineHeight);
    NSLog(@"Number of lines in label: %i", linesInLabel);

    [self.view addSubview:label];

}

或者,您可以用两行来完成:

[label sizeToFit];
int numLines = (int)(label.frame.size.height/label.font.leading);

关于iphone - UILabel 与 UILineBreakModeWordWrap 的结果行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4082041/

相关文章:

xcode - 在特定时间段后隐藏图像

iphone - 如何查找安装在 iPhone 中的应用程序

ios - 在单个 View 应用程序中使用 sprite kit

iphone - Storyboard和 uitableview 困境

ios - 无法在 native facebook 共享对话框中设置 ios9 中的初始文本

ios - 在 NSString 中添加空格?

iphone - 核心数据 : Find the property of NSEntity Objects in NSMutableSet

iphone - 使用 UISearchBar 关闭键盘,而不放弃第一响应者

iphone - iPhone SDK 如何在通讯录中创建联系人?

iphone - 从 iPhone 中的资源目录加载 PDF 文件崩溃