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):
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:
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?
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])];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With