// // NSMutableAttributedString+RYText.m // Asteria // // Created by 王猛 on 2024/1/6. // #import "NSMutableAttributedString+RYText.h" @implementation NSMutableAttributedString (RYText) - (void)setFont:(UIFont *)font { [self setFont:font range:NSMakeRange(0, self.length)]; } -(void)setColor:(UIColor *)color { [self setColor:color range:NSMakeRange(0, self.length)]; } - (void)setUnderlineStyle:(NSUnderlineStyle)underlineStyle { [self setUnderlineStyle:underlineStyle range:NSMakeRange(0, self.length)]; } - (void)setFont:(UIFont *)font range:(NSRange)range { [self setAttribute:NSFontAttributeName value:font range:range]; } - (void)setColor:(UIColor *)color range:(NSRange)range { [self setAttribute:NSForegroundColorAttributeName value:color range:range]; } - (void)setUnderlineStyle:(NSUnderlineStyle)underlineStyle range:(NSRange)range { NSNumber *style = underlineStyle == 0 ? nil : @(underlineStyle); [self setAttribute:NSUnderlineStyleAttributeName value:style range:range]; } - (void)setAttribute:(NSString *)name value:(id)value range:(NSRange)range { if (!name || [NSNull isEqual:name]) return; if (value && ![NSNull isEqual:value]) { [self addAttribute:name value:value range:range]; }else{ [self removeAttribute:name range:range]; } } #pragma mark - **************** get **************** - (UIFont *)font { return [self fontAtIndex:0]; } - (UIFont *)fontAtIndex:(NSUInteger)index { UIFont *font = [self attribute:NSFontAttributeName atIndex:index]; return font; } - (UIColor *)color { return [self colorAtIndex:0]; } - (UIColor *)colorAtIndex:(NSUInteger)index { UIColor *color = [self attribute:NSForegroundColorAttributeName atIndex:index]; if (!color) { CGColorRef ref = (__bridge CGColorRef)([self attribute:(NSString *)kCTForegroundColorAttributeName atIndex:index]); color = [UIColor colorWithCGColor:ref]; } if (color && ![color isKindOfClass:[UIColor class]]) { if (CFGetTypeID((__bridge CFTypeRef)(color)) == CGColorGetTypeID()) { color = [UIColor colorWithCGColor:(__bridge CGColorRef)(color)]; } else { color = nil; } } return color; } - (NSUnderlineStyle)strikethroughStyle { return [self strikethroughStyleAtIndex:0]; } - (NSUnderlineStyle)strikethroughStyleAtIndex:(NSUInteger)index { NSNumber *style = [self attribute:NSStrikethroughStyleAttributeName atIndex:index]; return style.integerValue; } - (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index { if (!attributeName) return nil; if (index > self.length || self.length == 0) return nil; if (self.length > 0 && index == self.length) index--; return [self attribute:attributeName atIndex:index effectiveRange:NULL]; } @end