比如,设置一个价格标签为(下图)的样式,其中就包括一个字符串里面设置价格为红色为,原价上面添加中划线,具体封装如下
NSMutableAttributedString常见的属性及说明
NSFontAttributeName 字体
NSParagraphStyleAttributeName 段落格式
NSForegroundColorAttributeName 字体颜色
NSBackgroundColorAttributeName 背景颜色
NSStrikethroughStyleAttributeName 删除线格式
NSUnderlineStyleAttributeName 下划线格式
NSStrokeColorAttributeName 删除线颜色
NSStrokeWidthAttributeName 删除线宽度
NSShadowAttributeName 阴影
调用方法,需要说明的是,这里的中划线是做了一个label放上去的,长度好像无法满足需求。
nowLabel.text = self.vipSource[0][i];
nowLabel.font = [UIFont fontWithName:@"STHeitiSC-Medium" size:20 * kWIDTH];
nowLabel.textColor = rgb(57, 107, 153);
// 调用设置特殊字体的方法
[[CustomLabelAttribute sharedInstance] attributeLabel:nowLabel size:nowLabel.font color:rgb(208, 89, 85)];
.h里面
#import <UIKit/UIKit.h>
@interface CustomLabelAttribute : NSObject
+ (instancetype)sharedInstance;
- (void)attributeLabel:(UILabel *)label size:(id)size color:(UIColor *)color;
-(void)attributeLabel:(UILabel *)label size:(id)size strikeColor:(UIColor *)strikeColor;
@end
.m里面
#import "CustomLabelAttribute.h"
@implementation CustomLabelAttribute
// 单例方法方
+ (instancetype)sharedInstance{
static CustomLabelAttribute *shareClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shareClient = [[CustomLabelAttribute alloc]init];
});
return shareClient;
}
// 设置特殊字体的方法
-(void)attributeLabel:(UILabel *)label size:(id)size color:(UIColor *)color{
NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:label.text];
NSRange range = [self findString:label.text];
// 设置字号
[str addAttribute:NSFontAttributeName value:size range:range];
// 设置字体的颜色
[str addAttribute:NSForegroundColorAttributeName value:color range:range];
label.attributedText = str;
}
- (NSRange)findString:(NSString *)str{
// 查找给定字符串的位置
NSRange range1 = [str rangeOfString:@"月"];
NSRange range2 = [str rangeOfString:@"元"];
return NSMakeRange(range1.location + 1, range2.location - range1.location - 1);
}
// 设置中划线的方法
-(void)attributeLabel:(UILabel *)label size:(id)size strikeColor:(UIColor *)strikeColor{
NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:label.text];
NSRange range = NSMakeRange(0, label.text.length);
// 设置字号
[str addAttribute:NSFontAttributeName value:size range:range];
// 设置划线的颜色
[str addAttribute:NSForegroundColorAttributeName value:strikeColor range:range];
// 加中划线
[str addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:range];
label.attributedText = str;
}
@end