iOS NSMutableAttributedString字符串属性

比如,设置一个价格标签为(下图)的样式,其中就包括一个字符串里面设置价格为红色为,原价上面添加中划线,具体封装如下

这里写图片描述

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值