2016-02-18 52 views
0

我认为这是一个常见问题,当你有一组单词时,你不想要断线。防止在NSAttributedString中换行

有时,这些词之间的字符是一个空格或连字符,等等。对我来说,这是一个点:)

这是我的文字50.0/80.0

最后我做到了使用尺寸标签和测量我需要多少空间对于字符串特别是:

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"]; 
    } 
} 

我发现了其他解决方案,如更换你的空间或连字符的字符牢不可破:

Preventing line breaks in part of an NSAttributedString

但我的问题是更普遍的,并NSAttributedString提供的东西来定义一组词作为非易碎的?或者是否有更简单的方法来处理一般词汇?

+0

使用'NSParagraphStyle',设置换行符模式为'ByWordWrapping',看到这个答案... http://stackoverflow.com/a/19197903/499581 –

+0

换行符使用\,而不是'/'虽然。你知道的,对吧? – LinusGeffarth

回答

2

不,NSAttributedString没有任何每字符属性可以防止某个范围内的换行符。您可以将NSLineBreakMode设置为ByClippingNSParagraphStyle中的其他非包装模式,但这适用于段落中的所有文本。 (段落之间用换行符分隔)

要防止在整个段落范围内发生较小范围的换行符,您需要在可能发生不必要的中断的任何两个字符之间插入U+2060 WORD JOINER。在你的例子中,这意味着在斜线字符的每一侧。

+0

我想你是指在角色角色的每一边,那个我不想破的角色。 我试过替换最后一个“。”。对于U + 2060.U + 2060,它不起作用。 即使我尝试在整个数字之间添加这些字符:U + 2060 50.0/80.0 U + 2060,但没有。 awardNumber = [NSString stringWithFormat:@“%@%@%@”,@“\ u2060”,awardNumber,@“\ u2060”]; – xarly

+0

另外我加了一段:NSMutableParagraphStyle * style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; [style setLineBreakMode:NSLineBreakByWordWrapping]; 'NSDictionary * attributes = @ {NSFontAttributeName:fontAwardNumber,NSParagraphStyleAttributeName:style}; NSMutableAttributedString * attributedStringAwardNumber = [[NSMutableAttributedString alloc] initWithString:awardNumber attributes:attributes]; – xarly