且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

iOS 创建带有图片的富文本

更新时间:2021-09-23 01:19:19

引言

需求:展示信用卡标签信息,当特性标签存在多个时自动换行显示。每行特性标签信息以icon开头。

iOS 创建带有图片的富文本

特性标签字段labelTitle

        "labelTitle" : "核卡105\r\n首刷后再补贴65",

应用场景:存在图片和文字并排展示,例如特性标签

iOS 创建带有图片的富文本

核心步骤

1、初始化NSTextAttachment对象,设置image以及布局

2、创建带有图片的富文本

原理

使用NSAttachmentAttributeName属性设置文本附件功能来插入图片使用NSTextAttachment对象

I、富文本如何添加图片?

1.1 初始化NSTextAttachment对象

   NSTextAttachment *attchment = [[NSTextAttachment alloc]init];
        
        
        
//设置frame,【可选】
        attchment.bounds=CGRectMake(0,0,14,14);
        

        attchment.image= [UIImage imageNamed:@"icon_jinrong_dagouicon"];//设置图片

bounds 属性的y 值为负数时是向下移动,正数反之。

  • NSBaselineOffsetAttributeName 基准线偏移 NSNumber可用于调整布局

1.2 创建带有图片的富文本

@interface NSAttributedString (NSAttributedStringAttachmentConveniences)
// A convenience method for creating an attributed string containing attachment using NSAttachmentCharacter as the base character.
+ (NSAttributedString *)attributedStringWithAttachment:(NSTextAttachment *)attachment API_AVAILABLE(macos(10.0), ios(7.0));
@end

创建带有图片的富文本

//1.初始化NSTextAttachment对象

        NSTextAttachment *attchment = [[NSTextAttachment alloc]init];
        
        
        
        
        attchment.bounds=CGRectMake(0,0,14,14);//设置frame
        
        
        attchment.image= [UIImage imageNamed:@"icon_jinrong_dagouicon"];//设置图片
        
        //2.创建带有图片的富文本
        
        NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attchment];

1.3 例子:展示信用卡标签


iOS 创建带有图片的富文本

#import <ChainAttributedString/NSMutableAttributedString+Chain.h>

- (NSMutableArray *)titleArr{
    NSMutableArray * tmp = [NSMutableArray arrayWithArray:[self.labelTitle componentsSeparatedByString:@"\r\n"]];
    
    [tmp removeObject:@""];
    [tmp removeObject:@" "];
    
    // 去除数组空字符串对象小技巧:iOS 利用NSSet和array的转换,进行快速去空去重
    NSSet *set = [NSSet setWithArray:tmp];
    NSArray *aaa = [set allObjects];
    
    
    return [NSMutableArray arrayWithArray:aaa];
    
    
    
}



- (NSMutableAttributedString*)getDtoNSMutableAttributedString4labelTitle{
    

    NSMutableAttributedString *attributedString  = [[NSMutableAttributedString alloc]init];
    
    
    for (NSString *title in self.titleArr) {
        
        NSLog(@"title:%@",title);
        
        if([NSStringQCTtoll isBlankString:title]){
            continue;
        }
        //1.初始化NSTextAttachment对象
        
        NSTextAttachment *attchment = [[NSTextAttachment alloc]init];
        
        
        attchment.bounds=CGRectMake(0,0,14,14);//设置frame
        
        
        attchment.image= [UIImage imageNamed:@"icon_jinrong_dagouicon"];//设置图片
        
        //2.创建带有图片的富文本
        
        NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attchment];
        
        [attributedString appendAttributedString:string];
        
        
        attributedString.kn_addString(@" ").kn_addString(title).kn_fontColor(rgba(0, 0, 0, 1)).kn_fontSize(kPingFangFont(13)).kn_addString(@"\n");
        
        
        
    }
    
    
    return attributedString;
    
}//    //    [attributedString insertAttributedString:string atIndex:0];//插入到第几个下标

II、基础知识

2.1 富文本属性

属性 用途 类型
NSFontAttributeName 字号 UIFont 默认12
NSParagraphStyleAttributeName 段落样式 NSParagraphStyle
NSForegroundColorAttributeName 前景色 UIColor
NSBackgroundColorAttributeName 背景色 UIColor
NSObliquenessAttributeName 字体倾斜 NSNumber
NSExpansionAttributeName 字体加粗 NSNumber 比例 0就是不变 1增加一倍
NSKernAttributeName 字间距 CGFloat
NSUnderlineStyleAttributeName 下划线 1或0
NSUnderlineColorAttributeName 下划线颜色 UIColor
NSStrikethroughStyleAttributeName 删除线 1或0
NSStrikethroughColorAttributeName 删除线颜色 UIColor
NSStrokeColorAttributeName same as ForegroundColor UIColor
NSStrokeWidthAttributeName 字体描边 CGFloat
NSLigatureAttributeName 连笔字 1或0
NSShadowAttributeName 阴影 NSShawdow
NSTextEffectAttributeName 设置文本特殊效果,目前只有图版印刷效果可用 NSString
NSAttachmentAttributeName 设置文本附件,常用插入图片 NSTextAttachment
NSLinkAttributeName 链接 NSURL (preferred) or NSString
NSBaselineOffsetAttributeName 基准线偏移 NSNumber,可用于布局
NSWritingDirectionAttributeName 文字方向 分别代表不同的文字出现方向@[@(1),@(2)]
NSVerticalGlyphFormAttributeName 水平或者竖直文本 1竖直 0水平
  • NSFontAttributeName 字号 UIFont 默认12
  • NSParagraphStyleAttributeName 段落样式 NSParagraphStyle
  • NSForegroundColorAttributeName 前景色 UIColor
  • NSBackgroundColorAttributeName 背景色 UIColor
  • NSObliquenessAttributeName 字体倾斜 NSNumber
  • NSExpansionAttributeName 字体加粗 NSNumber 比例 0就是不变 1增加一倍
  • NSKernAttributeName 字间距 CGFloat
  • NSUnderlineStyleAttributeName 下划线 1或0
  • NSUnderlineColorAttributeName 下划线颜色 UIColor
  • NSStrikethroughStyleAttributeName 删除线 1或0
  • NSStrikethroughColorAttributeName 删除线颜色 UIColor
  • NSStrokeColorAttributeName same as ForegroundColor UIColor
  • NSStrokeWidthAttributeName 字体描边 CGFloat
  • NSLigatureAttributeName 连笔字 1或0
  • NSShadowAttributeName 阴影 NSShawdow
  • NSTextEffectAttributeName 设置文本特殊效果,目前只有图版印刷效果可用 NSString
  • NSAttachmentAttributeName 设置文本附件,常用插入图片 NSTextAttachment
  • NSLinkAttributeName 链接 NSURL (preferred) or NSString
  • NSBaselineOffsetAttributeName 基准线偏移 NSNumber可用于调整布局
  • NSWritingDirectionAttributeName 文字方向 分别代表不同的文字出现方向 @[@(1),@(2)]
  • NSVerticalGlyphFormAttributeName 水平或者竖直文本 1竖直 0水平

2.2 布局小技巧

iOS 创建带有图片的富文本

下划线的top的约束参照对象是iconImgV和tagLab两者之间的Y的较大值

- (UILabel *)lineLab{
    if (nil == _lineLab) {
        UILabel *tmpView = [[UILabel alloc]init];
        _lineLab = tmpView;
        [self addSubview:_lineLab];
        tmpView.backgroundColor = k_tableView_Line;
        
        __weak __typeof__(self) weakSelf = self;
        [_lineLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(LineH);
            
            make.left.equalTo(weakSelf).offset(kAdjustRatio(10));
            make.right.equalTo(weakSelf).offset(kAdjustRatio(-10));
            make.bottom.equalTo(weakSelf);
            
            make.top.greaterThanOrEqualTo(weakSelf.iconImgV.mas_bottom).offset(kAdjustRatio(18));
            
            make.top.greaterThanOrEqualTo(weakSelf.tagLab.mas_bottom).offset(kAdjustRatio(18));

        }];
        
    }
    return _lineLab;
}

see also

iOS富文本使用指南【持续更新中】:

1、封装富文本API,采用block实现链式编程

2、 超链接属性

3、HTML字符串与富文本互转

4、在适配系统API的应用