iOSiOS

iOS - Label中的富文本+图文混排(2016-06-28

2016-06-28  本文已影响1238人  欧币杰昔

Label有text这个文本属性,要做到富文本效果,就需要用到富文本属性attributedText(textView、textField、UIButton中都有这个属性)

使用方法:

为某一范围内文字设置多个属性

为某一范围内文字添加某个属性

为某一范围内文字添加多个属性

移除某范围内的某个属性

常见的属性及说明

NSFontAttributeName 字体
NSParagraphStyleAttributeName 段落格式
NSForegroundColorAttributeName 字体颜色
NSBackgroundColorAttributeName 背景颜色
NSStrikethroughStyleAttributeName删除线格式
NSUnderlineStyleAttributeName 下划线格式
NSStrokeColorAttributeName 删除线颜色
NSStrokeWidthAttributeName删除线宽度
NSShadowAttributeName 阴影

先看下效果图:

Paste_Image.png

富文本实现方法:

1、声明属性:

@property(nonatomic,strong)UILabel*lblTest;//对象
@property(nonatomic,strong)NSMutableAttributedString*attri;//富文本对象
@property(nonatomic,strong)NSTextAttachment*attch;

2、初始化富文本对象并设置样式

//初始化Label
self.lblTest= [[UILabelalloc]initWithFrame:CGRectMake(0,0,280,40)];
self.lblTest.center=self.view.center;
self.lblTest.text=@"啤酒饮料矿泉水123456";
self.lblTest.textAlignment=1;
[self.viewaddSubview:self.lblTest];
//初始化富文本对象
self.attri= [[NSMutableAttributedStringalloc]initWithString:self.lblTest.text];
//修改富文本中的不同文字的样式
[self.attriaddAttribute:NSForegroundColorAttributeNamevalue:[UIColorgreenColor]range:NSMakeRange(7,6)];//字体颜色
[self.attriaddAttribute:NSForegroundColorAttributeNamevalue:[UIColorblueColor]range:NSMakeRange(0,3)];//字体颜色
[self.attriaddAttribute:NSFontAttributeNamevalue:[UIFontsystemFontOfSize:20]range:NSMakeRange(0,7)];//字体大小

3、用label的attributedText属性来使用富文本

// 用label的attributedText属性来使用富文本
self.lblTest.attributedText = self.attri;

这时实现的效果是这样的:

Paste_Image.png

实现图文混排:

步骤:

-创建NSTextAttachment的对象,用来装在图片
-将NSTextAttachment对象的image属性设置为想要使用的图片
-设置NSTextAttachment对象bounds大小,也就是要显示的图片的大小
-用[NSAttributedString attributedStringWithAttachment:attch]方法,将图片添加到富文本上

//初始化NSTextAttachment对象
self.attch = [[NSTextAttachment alloc]init];
//设置frame
self.attch.bounds = CGRectMake(0, 0, 40, 40);
//设置图片
self.attch.image = [UIImage imageNamed:@"源声-Logo"];
// 创建带有图片的富文本
NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:(NSTextAttachment *)(self.attch)];
//插入到第几个下标
[self.attri insertAttributedString:string atIndex:0];
//添加到尾部
[self.attri appendAttributedString:string];



// 用label的attributedText属性来使用富文本
self.lblTest.attributedText = self.attri;
Paste_Image.png

demo分享:链接: http://pan.baidu.com/s/1geKmEGF 密码: iyz8

上一篇下一篇

猜你喜欢

热点阅读