NSAttributedString, change the font overall BUT keep all other attributes?

前端 未结 6 884
长情又很酷
长情又很酷 2020-11-28 08:24

Say I have an NSMutableAttributedString .

The string has a varied mix of formatting throughout:

Here is an example:

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 08:55

    Obj-C version of @manmal's answer

    @implementation NSMutableAttributedString (Additions)
    
    - (void)setFontFaceWithFont:(UIFont *)font color:(UIColor *)color {
        [self beginEditing];
        [self enumerateAttribute:NSFontAttributeName
                         inRange:NSMakeRange(0, self.length)
                         options:0
                      usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
                          UIFont *oldFont = (UIFont *)value;
                          UIFontDescriptor *newFontDescriptor = [[oldFont.fontDescriptor fontDescriptorWithFamily:font.familyName] fontDescriptorWithSymbolicTraits:oldFont.fontDescriptor.symbolicTraits];
                          UIFont *newFont = [UIFont fontWithDescriptor:newFontDescriptor size:font.pointSize];
                          if (newFont) {
                              [self removeAttribute:NSFontAttributeName range:range];
                              [self addAttribute:NSFontAttributeName value:newFont range:range];
                          }
    
                          if (color) {
                              [self removeAttribute:NSForegroundColorAttributeName range:range];
                              [self addAttribute:NSForegroundColorAttributeName value:newFont range:range];
                          }
                      }];
        [self endEditing];
    }
    
    @end
    

提交回复
热议问题