如何根据文本长度计算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);