IOS--如何在UILabel上显示图片
前言
在做xmpp聊天的时候,大家不自然的就想到了能发文字能图片等等
关于如何在lab上显示图片笔者也是为了图个方便 用一个lab就能搞定可以显示文字也可以显示图片
1. 首先创建一个lable
self.lable =[[UILabel alloc]init];
self.lable.frame =CGRectMake(0, 100, 100, 100);
self.lable.backgroundColor =[UIColor clearColor];
[self.view addSubview:self.lable];
2. 生成文本附件
UIImage *img = [UIImage imageNamed:@"Chat_head"];
NSTextAttachment *textAttach = [[NSTextAttachment alloc]init];
textAttach.image = img;
3. 使用文本附件创建属性文本
NSAttributedString * strA =[NSAttributedString attributedStringWithAttachment:textAttach];
self.lable.attributedText = strA;
所有人都知道label.Text 但应该不是全都知道label.attributedText
使用文本附件给label的属性文本赋值。
实现图文混排功能
聊天时候会出现图文混排的情况, 其实实现也很简单
代码如下:
1. 创建一个lable 两个字符串
2. 创建一个可变的富文本 添加文字
3. 创建一个放置图片的富文本
4. 用label的attributedText属性来使用富文本
聊天时候会出现图文混排的情况, 其实实现也很简单
代码如下:
1. 创建一个lable 两个字符串
self.lable =[[UILabel alloc]init];
self.lable.frame =CGRectMake(0, 100, 200, 100);
self.lable.backgroundColor =[UIColor redColor];
self.lable.textColor = [UIColor greenColor];
[self.view addSubview:self.lable];
self.view.backgroundColor = [UIColor yellowColor];
NSString *str1 = @"延安路";
NSString *str2 = @"上塘路";
2. 创建一个可变的富文本 添加文字
// 创建一个富文本
NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@",str1,str2]];
// 修改富文本中的不同文字的样式
[attri addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, str1.length)];
[attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, str1.length)];
// 设置数字
[attri addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(str1.length, str2.length)];
[attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:NSMakeRange(str1.length, str2.length)];
3. 创建一个放置图片的富文本
// 添加表情
NSTextAttachment *attch = [[NSTextAttachment alloc] init];
// 表情图片
attch.image = [UIImage imageNamed:@"Chat_head"];
// 设置图片大小
attch.bounds = CGRectMake(0, 0, 40, 40);
// 创建带有图片的富文本
NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
[attri insertAttributedString:string atIndex:3];
4. 用label的attributedText属性来使用富文本
self.lable.attributedText = attri;