给富文本NSMutableAttributedString
扩展分类,添加自己封装的方法
NS_ASSUME_NONNULL_BEGIN
@interface NSMutableAttributedString (Ext)
- (instancetype)stringAppendString:(NSString *)string withAttr:(NSDictionary *)attr;
+ (instancetype)stringAppendString:(NSString *)string withAttr:(NSDictionary *)attr;
@end
NS_ASSUME_NONNULL_END
#import "NSMutableAttributedString+Ext.h"
@implementation NSMutableAttributedString (Ext)
+ (instancetype)stringAppendString:(NSString *)string withAttr:(NSDictionary *)attr {
NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] init];
[aString stringAppendString:string withAttr:attr];
return aString;
}
- (instancetype)stringAppendString:(NSString *)string withAttr:(NSDictionary *)attr {
if (attr == nil) {
attr = @{};
}
if (string && string.length) {
NSMutableAttributedString *multableAttrString = [[NSMutableAttributedString alloc] initWithString:string];
[multableAttrString setAttributes:attr range:NSMakeRange(0, string.length)];
[self appendAttributedString:multableAttrString];
}
return self;
}
@end
使用示例:
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableAttributedString *attr1 = [NSMutableAttributedString stringAppendString:@"船长" withAttr:@{NSForegroundColorAttributeName : [UIColor redColor]}];
NSMutableAttributedString *attr2 = [attr1 stringAppendString:@"学习录" withAttr:@{NSForegroundColorAttributeName : [UIColor blueColor]}];
NSMutableAttributedString *attr3 = [attr2 stringAppendString:@"之链式编程" withAttr:@{NSFontAttributeName : [UIFont systemFontOfSize:22],NSBackgroundColorAttributeName : [UIColor yellowColor]}];
self.label.attributedText = attr3;
}
Swift示例
extension NSMutableAttributedString {
@discardableResult
static func dx_AppendString(string: String, attr: Dictionary<NSAttributedString.Key, Any>? ) -> NSMutableAttributedString{
let attrs = NSMutableAttributedString.init(string: string, attributes: attr)
return attrs
}
@discardableResult
func dx_AppendString(string: String, attr: Dictionary<NSAttributedString.Key, Any>) -> Self{
if string.count > 0 {
let aString = NSMutableAttributedString.init(string: string)
aString.setAttributes(attr, range: NSRange.init(location: 0, length: string.count))
self.append(aString)
}
return self
}
}