Prevent line break in a NSAttributedString

帅比萌擦擦* 提交于 2020-01-13 05:26:27

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/35489781/prevent-line-break-in-a-nsattributedstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!