动态改变 UILabel 的字体大小 [英] Dynamically changing font size of UILabel
问题描述
我目前有一个 UILabel
:
factLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 280, 100)];
factLabel.text = @"some text some text some text some text";
factLabel.backgroundColor = [UIColor clearColor];
factLabel.lineBreakMode = UILineBreakModeWordWrap;
factLabel.numberOfLines = 10;
[self.view addSubview:factLabel];
在我的 iOS 应用程序的整个生命周期中,factLabel
获得了一堆不同的值.有些有多个句子,有些只有 5 或 6 个词.
Throughout the life of my iOS application, factLabel
gets a bunch of different values. Some with multiple sentences, others with just 5 or 6 words.
如何设置 UILabel
以便改变字体大小,使文本始终适合我定义的边界?
How can I set up the UILabel
so that the font size changes so that the text always fits in the bounds I defined?
推荐答案
单行:
factLabel.numberOfLines = 1;
factLabel.minimumFontSize = 8;
factLabel.adjustsFontSizeToFitWidth = YES;
上面的代码会将您的文本的字体大小调整为(例如)8
以尝试使您的文本适合标签.numberOfLines = 1
是强制性的.
The above code will adjust your text's font size down to (for example) 8
trying to fit your text within the label.
numberOfLines = 1
is mandatory.
多行:
对于 numberOfLines >1
有一种方法可以通过 NSString 来计算最终文本的大小sizeWithFont:... UIKit添加方法,例如:
For numberOfLines > 1
there is a method to figure out the size of final text through NSString's sizeWithFont:... UIKit addition methods, for example:
CGSize lLabelSize = [yourText sizeWithFont:factLabel.font
forWidth:factLabel.frame.size.width
lineBreakMode:factLabel.lineBreakMode];
之后,您可以使用生成的 lLabelSize
调整标签大小,例如(假设您将仅更改标签的高度):
After that you can just resize your label using resulting lLabelSize
, for example (assuming that you will change only label's height):
factLabel.frame = CGRectMake(factLabel.frame.origin.x, factLabel.frame.origin.y, factLabel.frame.size.width, lLabelSize.height);
iOS6
单行:
从 iOS6 开始,minimumFontSize
已被弃用.线
Starting with iOS6, minimumFontSize
has been deprecated. The line
factLabel.minimumFontSize = 8.;
可以改为:
factLabel.minimumScaleFactor = 8./factLabel.font.pointSize;
iOS7
多行:
从 iOS7 开始,sizeWithFont
被弃用.多行情况简化为:
Starting with iOS7, sizeWithFont
becomes deprecated.
Multiline case is reduced to:
factLabel.numberOfLines = 0;
factLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGSize maximumLabelSize = CGSizeMake(factLabel.frame.size.width, CGFLOAT_MAX);
CGSize expectSize = [factLabel sizeThatFits:maximumLabelSize];
factLabel.frame = CGRectMake(factLabel.frame.origin.x, factLabel.frame.origin.y, expectSize.width, expectSize.height);
iOS 13 (Swift 5):
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
这篇关于动态改变 UILabel 的字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!