【问题标题】:Calculate height and number of lines of the label计算标签的高度和行数
【发布时间】:2016-03-16 06:25:35
【问题描述】:

我有一个显示在UILabel 中的文本。但是,此文本有几个行空间,如下所示。现在,我想计算这个标签的高度,考虑换行符、粗体文本和字体大小。由于此文本不能放在标签中的单行中,因此可能有几行我们必须在运行时确定。基于这个高度,我想增加我的UILabel 的 y 坐标,所以UILabel 将始终卡在屏幕底部。 (只有高度会增加(向上))

我该如何解决这个问题?

NSAttributedString *linespace = [[NSAttributedString alloc] initWithString: @"\n"];

NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc]initWithString:@"Mathews is a " attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:40]}];  

NSAttributedString*    attributed = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@", @"Bad guy"] attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:40]}];


[mutableString appendAttributedString: linespace];

[mutableString appendAttributedString: attributed];

[mutableString appendAttributedString: linespace];

【问题讨论】:

  • 我觉得自动布局比计算高度更好

标签: ios objective-c


【解决方案1】:

你可以通过

得到高度
CGRect rectCountry = [mutableString boundingRectWithSize:(CGSize){@“YOUR WIDTH”, CGFLOAT_MAX}
                                                     options:NSStringDrawingUsesLineFragmentOrigin
                                                     context:nil];
CGSize sizeCountry = rectCountry.size;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    相关资源
    最近更新 更多