HTML標籤 轉 NSAttributedString

CocoaJason發表於2018-04-14
NSDictionary *options = @{
                              NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType
                              };
    NSAttributedString *attributeString = [[NSAttributedString alloc] initWithData:[@"<font color = 'blue' size = '8'>改革開放</font>  <font color = 'red' size = '30'>40</font>年" dataUsingEncoding:NSUnicodeStringEncoding] options:options documentAttributes:nil error:nil];
    
    NSRange range = NSMakeRange(0, attributeString.string.length);
    
    NSMutableAttributedString *mutableAttributeString = [[NSMutableAttributedString alloc] initWithAttributedString:attributeString];
    [attributeString enumerateAttributesInRange:range options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary<NSAttributedStringKey,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
        
        UIFont *oldFont = [attrs objectForKey:NSFontAttributeName];
        
        NSMutableDictionary *newattrs = [attrs mutableCopy];
        [newattrs setValue:[UIFont systemFontOfSize:oldFont.pointSize] forKey:NSFontAttributeName];
        
        [mutableAttributeString setAttributes:newattrs range:range];
        
    }];
複製程式碼