3

I think it's a common issue when you have a set of words where you don't want a break line.

Sometimes the character between those words is a space or a hyphen, etc. In my case it's a point :)

This is my text 50.0/80.0

At the end I did it using the size label and measuring how much space I need for that string in particular:

UIFont *fontAwardNumber = [UIFont fontWithName:@"DIN-Bold" size:20];

NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
CGSize labelSize = (CGSize){customCell.awardValueLabel.bounds.size.width, FLT_MAX};
CGRect rectNeededForAwardNumber = [awardNumber boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: fontAwardNumber} context:context];
if (rectNeededForAwardNumber.size.height > customCell.awardValueLabel.bounds.size.height) {
    //We need to add a breakline
    NSRange range = [awardNumber rangeOfString:@"/"];
    if (range.location != NSNotFound) {
        awardNumber = [awardNumber stringByReplacingCharactersInRange:range withString:@"/\n"];
    }
}

I found other solutions like replacing your space or hyphen for unbreakable characters:

Preventing line breaks in part of an NSAttributedString

But my question is more general, does NSAttributedString provide something to define a set of words as non breakable? Or is there any easier way to do it for a general set of words?

Community
  • 1
  • 1
xarly
  • 2,054
  • 4
  • 24
  • 40

1 Answers1

9

No, NSAttributedString doesn't have any per-character attributes that preventing line breaking within a range. You can set the NSLineBreakMode to ByClipping or another non-wrapping mode in the NSParagraphStyle, but that applies to all the text in the paragraph. (Paragraphs are separated by newlines.)

To prevent line breaking in a smaller range than a whole paragraph, you need to insert a U+2060 WORD JOINER between any two characters where an unwanted break might occur. In your example, that means on each side of the slash character.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • I guess you mean on each side of the point character, that the character I don't want to break. I've tried replacing the last "." for U+2060.U+2060, it didn't work. Even I tried adding those characters between the full number : U+2060 50.0/80.0 U+2060 but nothing. awardNumber = [NSString stringWithFormat:@"%@%@%@",@"\u2060",awardNumber,@"\u2060"]; – xarly Feb 19 '16 at 10:33
  • Also I added the paragraph: NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; [style setLineBreakMode:NSLineBreakByWordWrapping]; ' NSDictionary *attributes = @{NSFontAttributeName: fontAwardNumber, NSParagraphStyleAttributeName: style}; NSMutableAttributedString *attributedStringAwardNumber = [[NSMutableAttributedString alloc] initWithString:awardNumber attributes:attributes]; – xarly Feb 19 '16 at 10:41