如何根据文本长度计算UILabel宽度? [英] How to calculate UILabel width based on text length?

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

问题描述

我想在UILabel旁边显示一个图像,但UILabel有可变的文本长度,所以我不知道放置图像的位置。如何实现这个?

I want to display an image next to a UILabel, however UILabel has variable text length, so I don't know where to place the image. How can I accomplish this?

推荐答案

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font 
                        constrainedToSize:maximumLabelSize 
                        lineBreakMode:yourLabel.lineBreakMode]; 

What is -[NSString sizeWithFont:forWidth:lineBreakMode:] good for?

这个问题可能有你的答案,它为我工作。

this question might have your answer, it worked for me.

2014年,我编辑了这个新版本,基于诺贝尔下面!这做的一切。欢呼

For 2014, I edited in this new version, based on the ultra-handy comment by Norbert below! This does everything. Cheers

// yourLabel is your UILabel.

float widthIs = 
 [self.yourLabel.text
  boundingRectWithSize:self.yourLabel.frame.size                                           
  options:NSStringDrawingUsesLineFragmentOrigin
  attributes:@{ NSFontAttributeName:self.yourLabel.font }
  context:nil]
   .size.width;

NSLog(@"the width of yourLabel is %f", widthIs);

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

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