2013-10-07 25 views
2

請考慮長字符串,例如「位於美麗的巴爾的摩市中心」。UILabel:僅對文本的一部分應用換行符模式

我的標籤太小,這個文本,目前顯示它像這樣:

Located in beautiful downtown Ba…

我喜歡的位置串爲中心截斷不截斷「位於」子,像這樣:

坐落在美麗的... ltimore市

UILabel class reference表示這應該是可能的:

如果你想換行模式適用於文本的僅一部分,創建一個新的屬性串與所需的樣式信息,並將其與標籤相關聯。如果您未使用樣式文本,則此屬性適用於text屬性中的整個文本字符串。

在一個示例項目,只有一個的UILabel,我試圖遵循下面的代碼這些指令:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    NSString *firstPart = @"Located in"; 
    NSString *secondPart = @"beautiful downtown Baltimore City"; 
    NSString *joined = [NSString stringWithFormat:@"%@ %@", firstPart, secondPart]; 

    NSMutableAttributedString *joinedAttributed = [[NSMutableAttributedString alloc] initWithString:joined]; 

    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init]; 
    style.lineBreakMode = NSLineBreakByTruncatingMiddle; 

    NSRange detailRange = [joined rangeOfString:secondPart]; 

    [joinedAttributed addAttribute:NSParagraphStyleAttributeName value:style range:detailRange]; 

    self.label.attributedText = joinedAttributed; 
} 

我的標籤仍然出現相同的,並在最後的截斷。

這裏是最後的結果看起來像在調試器:

(lldb) po joinedAttributed 
Located in { 
}beautiful downtown Baltimore City{ 
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 5, Tabs (\n 28L,\n 56L,\n 84L,\n 112L,\n 140L,\n 168L,\n 196L,\n 224L,\n 252L,\n 280L,\n 308L,\n 336L\n), DefaultTabInterval 0, Blocks (null), Lists (null), BaseWritingDirection -1, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0"; 
} 

有沒有人得到這個工作?我的實現中缺少什麼?

+0

您是否嘗試過將UILabel的lineBreakMode設置爲NSLineBreakByTruncatingMiddle?似乎你應該得到你想要的東西,甚至不必與屬性文本混雜在一起。 –

+0

是;這將中心截斷整個字符串。期望的結果是中心截斷子字符串('secondPart')。 –

+0

那麼,你有沒有嘗試設置lineBreakMode的標籤,風格? –

回答

0

爲什麼不使用兩個UILabel s?第一個包含文本「位於」,然後第二個包含您想要的任何其他文本。然後,您可以將NSLineBreakByTruncatingMiddle屬性僅應用於第二個標籤。 你只需要把它們放在一起,就可以得到相同的錯覺UILabel

希望這會有所幫助!

+0

這種方法混亂的字體字距,所以它看起來不好。 –

相關問題