本文介绍了如何根据文本长度计算 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.


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 宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-03 03:07