NSAttributed string in multiple lines in UILabel

I have a UILabel inside a cell that contains several elements. I need the label to assign a string that can fill the height of the label, i.e. Skip multiple lines if necessary. I managed to do this, and if I launched the application on iOS7, it looks just fine (ignore the yellow background color): enter image description here

Here is the UILabel setup:

 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 I'm talking about. In the xib file for the cell, I set the minimum font size to 3 and the number of lines to 0. As I said, it works fine on iOS 7, but on iOS 6 for some reason it does not know how to make the word wrapping on it own and tries to "Truncate the tail", since this is the line break mode, which was set by default in xib, as a result of which the cell looks like this: enter image description here

If I change the line break mode to Word Wrapping, it will disable the application 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?

+7
ios uilabel multiline nsattributedstring
source share
3 answers

The problem was using the font (Helvetica custom font). I changed [AppereanceConfiguration fontMediumWithSize:18] to [UIFont boldSystemFontOfSize:16] and it works now. I assume that he was having trouble calculating the required width due to the custom font.

+3
source share

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

You can do it like this:

 NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; [YourMutableString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [YourMutableString length])]; 
+12
source share

try it

  [self.notificationText setAdjustsFontSizeToFitWidth:NO]; 

maybe even for iOS6

 if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) { //* [self.notificationText setAdjustsFontSizeToFitWidth:NO]; } 
+1
source share

All Articles