2012-10-03 66 views
17

在故事板中,我佈置了一組帶有各種格式選項的標籤。更改屬性UILabel的文本而不會丟失格式?

然後我做的:

label.text = @"Set programmatically"; 

和所有格式都將丟失!這在iOS5中運行良好。

必須有一種方法來更新文本字符串而不用重新編碼所有的格式?!

label.attributedText.string 

是隻讀的。

在此先感謝。

回答

3

一個屬性字符串包含它的所有格式化數據。標籤根本不知道有關格式的任何信息。

你可能屬性存儲爲一個單獨的字典,然後當你改變attributedString你可以使用:

[[NSAttributedString alloc] initWithString:@"" attributes:attributes range:range]; 

唯一的另一種選擇是再次搭建起完整的屬性。

28

您可以提取屬性與字典:

NSDictionary *attributes = [(NSAttributedString *)label.attributedText attributesAtIndex:0 effectiveRange:NULL]; 

然後用新的文本添加回:

label.attributedText = [[NSAttributedString alloc] initWithString:@"Some text" attributes:attributes]; 

這是假設標籤中有文字,否則你會崩潰,所以你應該首先執行檢查:

if ([self.label.attributedText length]) {...} 
+0

事實上,iOS的默認情況下應做的吧,反正我們有我們的方式。 謝謝,你的建議幫助了我。 –

4

雖然新增iOS程序我很快就遇到了同樣的問題。在iOS中,我的經驗是一致的時提取並重新應用的屬性並 不行的

  • 約瑟夫的建議

    1. Lewis42的問題:一個空屬性返回字典。

    說完看了看周圍的S/O,我碰到This Post和遵循的建議,我結束了使用此:

    - (NSMutableAttributedString *)SetLabelAttributes:(NSString *)input col:(UIColor *)col size:(Size)size { 
    
    NSMutableAttributedString *labelAttributes = [[NSMutableAttributedString alloc] initWithString:input]; 
    
    UIFont *font=[UIFont fontWithName:@"Helvetica Neue" size:size]; 
    
    NSMutableParagraphStyle* style = [NSMutableParagraphStyle new]; 
    style.alignment = NSTextAlignmentCenter; 
    
    [labelAttributes addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, labelAttributes.length)]; 
    [labelAttributes addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, labelAttributes.length)]; 
    [labelAttributes addAttribute:NSForegroundColorAttributeName value:col range:NSMakeRange(0, labelAttributes.length)]; 
    
    return labelAttributes; 
    
  • 相關問題