我知道这应该非常简单,但我一直在努力以编程方式创建 UILabel 并让它按照我想要的方式运行。
我想要的只是能够创建一个标签,设置高度、宽度和字体大小等最大属性,然后让文本变小和/或只是截断文本以容纳长文本字符串。
假设我希望我的标签的文本最大宽度为 380,最大高度为 20,最大字体大小为 12。
所以这是我试图创建这样一个标签的方法:
UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(91, 15, 0, 0)];
fromLabel.text = [self fromSender];
fromLabel.font = [UIFont fontWithName:ProximaNovaSemibold size:12]; //custom font
fromLabel.numberOfLines = 1;
fromLabel.baselineAdjustment = YES;
fromLabel.adjustsFontSizeToFitWidth = YES;
fromLabel.adjustsLetterSpacingToFitWidth = YES;
fromLabel.size = [fromLabel.text sizeWithFont:fromLabel.font constrainedToSize:CGSizeMake(380, 20) lineBreakMode:NSLineBreakByTruncatingTail];
fromLabel.minimumScaleFactor = MIN_SCALE_FACTOR;
fromLabel.clipsToBounds = YES;
fromLabel.backgroundColor = [UIColor clearColor];
fromLabel.textColor = [UIColor blackColor];
fromLabel.textAlignment = NSTextAlignmentLeft;
[collapsedViewContainer addSubview:fromLabel];
好的,标 checkout 现了,但是文本大于 12,高度总是 21!?即使我将高度和文本大小值更改为极端大小,此代码也会创建一个无法调整的固定大小的标签。我似乎唯一可以变小的是宽度。
我一定是忽略了一些基本的东西,但我真的不知道如何得到我想要的结果,我也不明白为什么我会得到我得到的行为。
最佳答案
以下是否有效?
UIFont * customFont = [UIFont fontWithName:ProximaNovaSemibold size:12]; //custom font
NSString * text = [self fromSender];
CGSize labelSize = [text sizeWithFont:customFont constrainedToSize:CGSizeMake(380, 20) lineBreakMode:NSLineBreakByTruncatingTail];
UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(91, 15, labelSize.width, labelSize.height)];
fromLabel.text = text;
fromLabel.font = customFont;
fromLabel.numberOfLines = 1;
fromLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines; // or UIBaselineAdjustmentAlignCenters, or UIBaselineAdjustmentNone
fromLabel.adjustsFontSizeToFitWidth = YES;
fromLabel.adjustsLetterSpacingToFitWidth = YES;
fromLabel.minimumScaleFactor = 10.0f/12.0f;
fromLabel.clipsToBounds = YES;
fromLabel.backgroundColor = [UIColor clearColor];
fromLabel.textColor = [UIColor blackColor];
fromLabel.textAlignment = NSTextAlignmentLeft;
[collapsedViewContainer addSubview:fromLabel];
编辑:我相信您在同时使用 adjustsFontSizeToFitWidth
和 minimumScaleFactor
时可能会遇到问题。前者声明您还需要设置一个 minimumFontWidth
(否则根据我的测试,它可能会缩小到一些完全不可读的东西),但这已被弃用并被后者取代。
编辑 2:没关系,过时的文档。 adjustsFontSizeToFitWidth
需要 minimumScaleFactor
,只需确保不将 0 作为 minimumScaleFactor 传递(整数除法,10/12 返回 0)。
baselineAdjustment
值也有细微变化。
关于ios - 以编程方式创建 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17813121/