#import <UIKit/UIKit.h>
@interface UILabel (AttributedString)
- (void)setTextFont:(UIFont *)font atRange:(NSRange)range;
- (void)setTextColor:(UIColor *)color atRange:(NSRange)range;
- (void)setTextLineSpace:(float)space atRange:(NSRange)range;
- (void)setTextFont:(UIFont *)font color:(UIColor *)color atRange:(NSRange)range;
- (void)setTextAttributes:(NSDictionary *)attributes atRange:(NSRange)range;
@end
#import "UILabel+AttributedString.h"
@implementation UILabel (AttributedString)
- (void)setTextFont:(UIFont *)font atRange:(NSRange)range
{
[self setTextAttributes:@{NSFontAttributeName : font}
atRange:range];
}
- (void)setTextColor:(UIColor *)color atRange:(NSRange)range
{
[self setTextAttributes:@{NSForegroundColorAttributeName : color}
atRange:range];
}
- (void)setTextLineSpace:(float)space atRange:(NSRange)range
{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:space];//调整行间距
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.text length])];
self.attributedText = attributedString;
[self sizeToFit];
}
- (void)setTextFont:(UIFont *)font color:(UIColor *)color atRange:(NSRange)range
{
[self setTextAttributes:@{NSFontAttributeName : font,
NSForegroundColorAttributeName : color}
atRange:range];
}
- (void)setTextAttributes:(NSDictionary *)attributes atRange:(NSRange)range
{
NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
for (NSString *name in attributes)
{
[mutableAttributedString addAttribute:name value:[attributes objectForKey:name] range:range];
}
// [mutableAttributedString setAttributes:attributes range:range]; error
self.attributedText = mutableAttributedString;
}
@end