现在遇到这样一个需求:Lable中显示的文字需要用一个引号来括住
这个时候需要借助Label的Attributstring中textAttachment,需要在文字中的哪个部位放置图片,我们就将该文字从哪段切开,然后在末尾添加图片(如果要在开头添加,只需要拼接一段" "在末尾添加上图片即可),具体的代码实现如下:
- (void)insertPictureInLabel { NSTextAttachment *foreAttachment = [[NSTextAttachment alloc]init]; foreAttachment.image = [UIImage imageNamed:@"bl_ios_splb_qyh"]; foreAttachment.bounds = CGRectMake(0, 0, 15, 15); NSTextAttachment *backAttachment = [[NSTextAttachment alloc]init]; backAttachment.image = [UIImage imageNamed:@"bl_ios_splb_hyh"]; backAttachment.bounds = CGRectMake(0, 0, 15, 15); NSMutableAttributedString *orginalAttributString = [[NSMutableAttributedString alloc]initWithString:@""]; NSAttributedString *firsString = [NSAttributedString attributedStringWithAttachment:foreAttachment]; [orginalAttributString appendAttributedString:firsString]; UILabel *pictureLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 64, screenSize.width - 100, 150)]; pictureLabel.backgroundColor = [UIColor clearColor]; NSMutableAttributedString *newAttributString = [[NSMutableAttributedString alloc]initWithString:@" 现在说的一些可能比较基础,大家会比较没兴趣,可是基础是练成高超技术的基石,趁着写博客的时候我自己也回顾一下这些基础知识,如果需要的demo的话我再发上来 "]; pictureLabel.font = [UIFont systemFontOfSize:15]; pictureLabel.numberOfLines = 0; NSAttributedString *secondString = [NSAttributedString attributedStringWithAttachment:backAttachment]; [newAttributString appendAttributedString:secondString]; [orginalAttributString appendAttributedString:newAttributString]; pictureLabel.attributedText = orginalAttributString; [self.view addSubview:pictureLabel]; }
原文:http://www.cnblogs.com/Mike-Fighting/p/4875515.html