2016-02-18 47 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