防止 NSAttributedString 中的换行符 [英] Prevent line break in a NSAttributedString
问题描述
我认为当您有一组不想要换行符的单词时,这是一个常见问题.
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 :)
这是我的文字 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:
防止 NSAttributedString 的一部分出现换行
但我的问题更笼统,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?
推荐答案
不,NSAttributedString
没有任何防止范围内换行的每字符属性.您可以将 NSLineBreakMode
设置为 ByClipping
或 NSParagraphStyle
中的其他非换行模式,但这适用于段落中的所有文本.(段落由换行符分隔.)
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.)
为了防止在比整个段落更小的范围内换行,您需要插入一个 U+2060任意两个字符之间的 WORD JOINER,其中可能会出现不需要的中断.在您的示例中,这意味着在斜杠字符的每一侧.
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.
这篇关于防止 NSAttributedString 中的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!