如何计算具有固定宽度的UILabel的行数? [英] How can I compute the number of lines of a UILabel with a fixed width?

查看:112
本文介绍了如何计算具有固定宽度的UILabel的行数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算具有固定宽度和给定文本的UILabel的行数?

How can I compute the number of lines of a UILabel with a fixed width and a given text ?

推荐答案

此代码假设标签具有所需的文本,并且其框架已设置为所需的宽度。

This code assumes label has the desired text and its frame is already set to the desired width.

- (int)lineCountForLabel:(UILabel *)label {
    CGSize constrain = CGSizeMake(label.bounds.size.width, FLT_MAX);
    CGSize size = [label.text sizeWithFont:label.font constrainedToSize:constrain lineBreakMode:UILineBreakModeWordWrap];

    return ceil(size.height / label.font.lineHeight);
}

更新

如果您只想根据文本和当前宽度确定标签所需的高度,请将其更改为:

If all you want is to determine the required height for the label based on its text and current width, then change this to:

- (CGSize)sizeForLabel:(UILabel *)label {
    CGSize constrain = CGSizeMake(label.bounds.size.width, FLT_MAX);
    CGSize size = [label.text sizeWithFont:label.font constrainedToSize:constrain lineBreakMode:UILineBreakModeWordWrap];

    return size;
}

返回的尺寸是包含标签的正确宽度和高度。

The returned size is the proper width and height to contain the label.

这篇关于如何计算具有固定宽度的UILabel的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆