Appending NSAttributedString with line break returns attributed string with wrong format

不问归期 提交于 2019-12-09 07:41:43

问题


I'm using NSMutableAttributedString and NSAttributedString to display a label text in two different font sizes. My approach is:

NSMutableAttributedString *muAtrStr = [[NSMutableAttributedString alloc]initWithString:@"2"];
NSAttributedString *atrStr = [[NSAttributedString alloc]initWithString:@"days" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}];
[muAtrStr appendAttributedString:atrStr];

Which returns me an Attributed string with "2" in font size 12 and "days" in font size 8.

However, the other scenario is to add a line break after 2. I use the following code:

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

This time attributed string applies the attribute on the full text. I get an attributed string with "2\ndays" in font size 8.


回答1:


Try this below code, it works fine:-

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];

Note:- Also put numberOfLines to 0 for allowing any number of lines




回答2:


This works in Swift:

let attributedText = NSAttributedString(string: "Happy \nDays")
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.attributedText = attributedText


来源:https://stackoverflow.com/questions/22681008/appending-nsattributedstring-with-line-break-returns-attributed-string-with-wron

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