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?
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.
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