Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSAttributed string in multiple lines in a UILabel

I have a UILabel inside a cell which contains several elements. I need the label to have attributed string which can fill the label's height, i.e. go into multiple lines if neccessary. I managed to achieve this and if I run the App on iOS7 it appears to be just fine(disregard the yellowish background color):

enter image description here

Here is the setup of the UILabel:

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@  %@", sender, content]];
NSRange selectedRange = NSMakeRange(0, sender.length); // 4 characters, starting at index 22

[string beginEditing];

[string addAttribute:NSFontAttributeName
               value:[AppereanceConfiguration fontMediumWithSize:18]
               range:selectedRange];

[string endEditing];

self.notificationText.attributedText = string;

where self.notificationText is the UILabel that I'm talking about. In the xib file for the cell I've set the minimum font size to 3 and the number of lines to 0. As I said before, it works perfectly on iOS 7, but on iOS 6 for some reason it doesn't know how to do the word wrapping on it's own and it tries to "Truncate Tail" as this is the line break mode that has been set by default in the xib, resulting in a cell looking like this:

enter image description here

If I change the line break mode to Word Wrapping it crashes the app on iOS 6 saying that:

NSAttributedString invalid for autoresizing, it must have a single spanning paragraph style (or none) with a non-wrapping lineBreakMode.

How do I get this to work on iOS 6?

like image 847
damjandd Avatar asked Dec 06 '13 14:12

damjandd


2 Answers

You can get it to work on iOS 6 by doing exactly what the compiler states. For whatever reason, you need to add a NSParagraphStyle attribute to your NSAttributedString in order for this to work on iOS 6.

You can do it like so:

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
[YourMutableString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [YourMutableString length])];
like image 65
JustAnotherCoder Avatar answered Oct 22 '22 02:10

JustAnotherCoder


The problem was with the font I was using (a custom Helvetica font). I changed [AppereanceConfiguration fontMediumWithSize:18] for [UIFont boldSystemFontOfSize:16] and now it works. I guess that it had trouble calculating the necessary width because of the custom font.

like image 3
damjandd Avatar answered Oct 22 '22 04:10

damjandd