ios - 动态改变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 个单词。

如何设置 UILabel 以更改字体大小以使文本始终符合我定义的范围?

最佳答案

单行:

factLabel.numberOfLines = 1;
factLabel.minimumFontSize = 8;
factLabel.adjustsFontSizeToFitWidth = YES;

上面的代码会将您的文本的字体大小调整为(例如)8 试图使您的文本适合标签内。 numberOfLines = 1 是必填项。

多行:

对于numberOfLines > 1,有一种方法可以通过NSString's sizeWithFont:... UIKit addition计算出最终文本的大小。方法,例如:

CGSize lLabelSize = [yourText sizeWithFont:factLabel.font
                                  forWidth:factLabel.frame.size.width
                             lineBreakMode:factLabel.lineBreakMode];

之后,您可以使用生成的 lLabelSize 调整标签大小,例如(假设您只更改标签的高度):

factLabel.frame = CGRectMake(factLabel.frame.origin.x, factLabel.frame.origin.y, factLabel.frame.size.width, lLabelSize.height);

iOS6

单行:

从 iOS6 开始,minimumFontSize 已被弃用。线

factLabel.minimumFontSize = 8.;

可以改为:

factLabel.minimumScaleFactor = 8./factLabel.font.pointSize;

iOS7

多行:

从 iOS7 开始,sizeWithFont 被弃用。 多行大小写简化为:

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

https://stackoverflow.com/questions/4865458/

相关文章:

objective-c - 是否可以刷新 UITableView 中的单个 UITableViewC

ios - 具有 UITapGestureRecognizer 的 View 中的 UIButton

ios - UIImageView 上的 UIGestureRecognizer

objective-c - 为什么 Objective-C 委托(delegate)通常被赋予属性分

objective-c - 如何等待异步调度的 block 完成?

objective-c - 项目构建中的 CocoaPods 错误

ios - 在 Objective-C 中检查空字符串的正确方法是什么?

objective-c - Objective-C 中的方法语法

ios - Storyboard 中的 Modal 和 Push segue 有什么区别?

ios - 从 UIView 到 UIViewController?