How to calculate the size of a UIFont when text in label is constrained down to fit width?

南笙酒味 提交于 2019-12-18 16:56:51

问题


Imagine a UILabel, which is 200 pixels wide and 50 pixels high. The label has text inside, and the label makes the text smaller so that it fits into the label. But now, how would you get the size of that UIFont how it is visible in the label? Lets imagine the font size was given with huge 100, and the label squeezes it down to 15. And then, you want to make some other labels with little text, which has same font size. Is there a way to obtain the UIFont's font size after getting squeezed by the label?


回答1:


If you pass the size of the UILabel and the breakMode, etc. to:

CGSize  size = [label.text sizeWithFont:label.font minFontSize:10 actualFontSize:&actualFontSize forWidth:200 lineBreakMode:UILineBreakModeTailTruncation];

actualFontSize should be what you are looking for.

UPDATE:

The above has been deprecated. The method to use now is:

- (CGRect)textRectForBounds:(CGRect)bounds
     limitedToNumberOfLines:(NSInteger)numberOfLines

Here's an example

CGSize  size = [label textRectForBounds:label.bounds
     limitedToNumberOfLines:1].size;


来源:https://stackoverflow.com/questions/1385338/how-to-calculate-the-size-of-a-uifont-when-text-in-label-is-constrained-down-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!