NSAttributedString ignores Autoshrink and numberOfLines for UILabel (iOS 6)

别说谁变了你拦得住时间么 提交于 2019-12-20 08:48:21

问题


I have UILabel with number of lines = 2 system font size = 15 minimum font size = 8 Line break mode - Truncate tail

When I set long text which have type NSString for UILabel it works fine and shows multiline text (scaled if needed). When I am trying to set text with type NSAttributedString it ignores minimum font size and Autoshrink so I see one line text with maximum font size.

Is it possible to solve this problem

Looks something like this (Label size is const)

-----------------------
| normal NSString  Text|
| very  very  long ... | 
-----------------------

---------------------------
|NSAttributedString tex...|
---------------------------

回答1:


I found a way to do this:

label.adjustsFontSizeToFitWidth = true
label.attributedText = attributedString
label.lineBreakMode = .ByTruncatingTail // this did the trick!

It only works if the third line is set after setting the attributed string. It seems like the attributed string overrides line break behavior when set (among other things).




回答2:


minimumFontSize is deprecated as of iOS6. Additionally, adjustsFontSizeToFitWidth only works when numberOfLines is set to 1. UILabel will not resize text across multiple lines because there is ambiguity around handling line breaks while shrinking the font.

Use minimumScaleFactor to set the smallest size that the text should be scaled.

The following code will populate a UILabel with attributed string of font size 20, and scale it down by half to a minimum size of 10.

self.label.lineBreakMode = NSLineBreakByTruncatingTail;
NSMutableAttributedString *hogan = [[NSMutableAttributedString alloc] initWithString:@"Presenting the great... Hulk Hogan! Presenting the great... Hulk Hogan! Presenting the great... Hulk Hogan! Presenting the great... Hulk Hogan! Presenting the great... Hulk Hogan! Presenting the great... Hulk Hogan! Presenting the great... Hulk Hogan!"];
[hogan addAttribute:NSFontAttributeName
              value:[UIFont systemFontOfSize:20.0]
              range:NSMakeRange(0, [hogan length])];
[self.label setAttributedText:hogan];
self.label.adjustsFontSizeToFitWidth = YES;
self.label.numberOfLines = 1;
self.label.minimumScaleFactor = 0.5;



回答3:


NSMutableAttributedString *muAtrStr = [[NSMutableAttributedString alloc]initWithString:@"2"];
NSAttributedString *atrStr = [[NSAttributedString alloc]initWithString:@"\ndays" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}];
[muAtrStr appendAttributedString:atrStr];
self.lbl.numberOfLines = 0;
[self.lbl setAttributedText:muAtrStr];


来源:https://stackoverflow.com/questions/21290234/nsattributedstring-ignores-autoshrink-and-numberoflines-for-uilabel-ios-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!