如何计算特定字体和字体大小的文本字符串的宽度? [英] How to calculate the width of a text string of a specific font and font-size?
问题描述
我有一个UILabel显示一些字符。像x,y或rpm。如何计算标签中的文本宽度(它不会占用整个可用空间)?这是为了自动布局,如果UILabel里面有一个较小的文本,另一个视图将有一个更大的框架矩形。当指定UIFont和字体大小时,是否有方法来计算文本的宽度?
I have a UILabel that displays some chars. Like "x", "y" or "rpm". How can I calculate the width of the text in the label (it does not ues the whole available space)? This is for automatic layouting, where another view will have a bigger frame rectangle if that UILabel has a smaller text inside. Are there methods to calculate that width of the text when a UIFont and font size is specified? There's also no line-break and just one single line.
推荐答案
你可以通过各种 sizeWithFont:
中的方法 NSString UIKit添加。在你的情况下,最简单的变体应该足够了(因为你没有多行标签):
You can do exactly that via the various sizeWithFont:
methods in NSString UIKit Additions. In your case the simplest variant should suffice (since you don't have multi-line labels):
NSString *someString = @"Hello World";
UIFont *yourFont = // [UIFont ...]
CGSize stringBoundingBox = [someString sizeWithFont:yourFont];
此方法有多种变体,例如。有些考虑换行模式或最大尺寸。
There are several variations of this method, eg. some consider line break modes or maximum sizes.
这篇关于如何计算特定字体和字体大小的文本字符串的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!