xcode iOS - 使用属性文本自动收缩 UILabel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14798500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS - Auto-shrink UILabel with Attributed text
提问by Oleg
I have UILabel
which contains two attributed strings separated by a new line.
FIrst string has font size set to 17 and the second one to 14.
I want my first NSMutableAttributedString
be resized to minimum font size if its content can't fit in a single line.
我有UILabel
它包含两个由新行分隔的属性字符串。第一个字符串的字体大小设置为 17,第二个字符串设置为 14。NSMutableAttributedString
如果它的内容不能放在一行中,我希望我的第一个字符串被调整为最小字体大小。
Is that possible?
那可能吗?
It is pretty simple to configure such UILabel
behaviour by setting "auto shrink to minimum font size" in IB for plain text, but don't know how to do it for attributed text.
UILabel
通过在 IB 中为纯文本设置“自动缩小到最小字体大小”来配置此类行为非常简单,但不知道如何为属性文本执行此操作。
Here is my code:
这是我的代码:
NSString *eventName = @"Looong Event Name";
NSString *placeString = @"My place";
eventName = [eventName stringByAppendingString:@"\n"];
NSMutableAttributedString *attrName = [[NSMutableAttributedString alloc] initWithString:eventName];
[attrName addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:17] range:NSMakeRange(0, [eventName length])];
NSMutableAttributedString *attrPlace = [[NSMutableAttributedString alloc] initWithString:placeString];
[attrPlace addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, placeString.length)];
[attrPlace addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, placeString.length)];
NSMutableAttributedString *finalString = [[NSMutableAttributedString alloc] initWithAttributedString:attrName];
[finalString appendAttributedString:attrPlace];
UILabel *nameLabel = (UILabel *)[cell viewWithTag:100];
nameLabel.attributedText = finalString;
采纳答案by jrturton
I guess this is a follow on from your earlier question.
我想这是您之前问题的后续。
I don't think you can do this automatically, but there is a size
method of NSAttributedString which you can use to check if your string is too big, and adjust yourself if required.
我不认为您可以自动执行此操作,但是有一种size
NSAttributedString 方法可以用来检查您的字符串是否太大,并在需要时自行调整。