2017-04-24 71 views
0

嗨,我是新的目標C.我將htmlString轉換爲NSMutableAttributedString。但是當我更改NSMutableAttributedString的字體大小時,它會從我的文本中刪除粗體字體,請提供任何解決方案。更改NSMutableAttributedString的字體大小而不刪除粗體格式。

我的代碼:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil ]; 



     if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
     { 
//   overView.font = [UIFont systemFontOfSize:16]; 
      [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, attributedString.length)]; 
     } 
     else{ 
//   overView.font = [UIFont systemFontOfSize:12]; 
      [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange(0, attributedString.length)]; 
     } 
     overView.attributedText = (NSAttributedString *)attributedString; 

任何幫助,將不勝感激感謝。

+0

不是**它**,你這樣做。還有一個'boldSystemFontOfSize'方法。 – vadian

+0

@vadian它會將所有字符串加粗。 – Furqan

+0

當然,因爲範圍是爲整個字符串指定的。如果你想要一個部分字符串,你必須調整範圍。 – vadian

回答

0

試試這個。您需要使用複製字符串來顯示更改的字符串。

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil ]; 
    NSMutableAttributedString* copy = [attributedString mutableCopy]; 
    [attributedString enumerateAttributesInRange:NSMakeRange(0, string.length) options:0 usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) { 
    UIFont* font = attrs[NSFontAttributeName]; 
    if(font) 
    { 
     NSMutableDictionary* changedAttributes = [attrs mutableCopy]; 
     if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
     { 
     changedAttributes[NSFontAttributeName] = [UIFont fontWithName:font.fontName size:16]; 
     } 
     else{ 
     changedAttributes[NSFontAttributeName] = [UIFont fontWithName:font.fontName size:12]; 
     } 
     [copy setAttributes:changedAttributes range:range]; 
    } 
    }]; 
+0

它不工作。 – Furqan

+0

你確定使用** copy **顯示字符串嗎?因爲這個對象的所有變化,而不是一個歸屬的String。 – Sergey

+0

overView.attributedText =(NSAttributedString *)copy; 我正在這樣做。但不工作。 – Furqan