之前寫過,改變字型顔色字号等功能,這次咱們來來看看,NSMutableAttributedString 的延伸使用,富文本編輯,效果與圖文混排類似。
直接上代碼不多說了:
//
// ViewController.m
// AAAA
//
// Created by a111 on 16/7/12.
// Copyright © 2016年 司小文. All rights reserved.
//
#import "ViewController.h"
@interface ViewController (){
UILabel *_lab_AAAA;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self makeUI];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)makeUI{
_lab_AAAA = [[UILabel alloc] init];
_lab_AAAA.numberOfLines = 0;
_lab_AAAA.text = @"任天堂開發的AR手遊《精靈寶可夢GO》可謂引起了一時轟動,該遊戲于上周在美國、澳洲和紐西蘭地區上架,這讓其它地區苦等的粉絲非常失望,由于太過火爆,該公司還對IP進行了封鎖,中國區目前仍無法玩。但好消息是其它地區的使用者不用等太久了,現據《華爾街日報》報道,《精靈寶可夢GO》将于“近幾天内”登陸歐洲和亞洲地區,值得一提的是,該消息并非來自任天堂官方,而是了解遊戲計劃的消息人士。由于遊戲大熱,也促進了任天堂股價一度飙漲23%。希望任天堂不要辜負玩家們的熱情,能為遊戲提供更好的支援。";
[self setupEmojiAndLink];
[self.view addSubview:_lab_AAAA];
CGRect shopLabRect = [_lab_AAAA.attributedText boundingRectWithSize:CGSizeMake(self.view.frame.size.width-20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
_lab_AAAA.frame = CGRectMake(10, 100,shopLabRect.size.width, 300);
}
/**
* 向文本中添加表情等
*/
- (void)setupEmojiAndLink
{
NSMutableAttributedString * mutStr = [_lab_AAAA.attributedText mutableCopy];
//添加表情
for ( int i = 0; i< mutStr.length/50 ; i++) {
//建立一個圖檔
UIImage * image1 = [UIImage imageNamed:[NSString stringWithFormat:@"%d.jpeg",arc4random()%3+1]];
NSTextAttachment * attachment1 = [[NSTextAttachment alloc] init];
attachment1.bounds = CGRectMake(0, -1, 30, 30);
attachment1.image = image1;
NSAttributedString * attachStr1 = [NSAttributedString attributedStringWithAttachment:attachment1];
//最後一個參數為圖檔在證據話的位置下标。
[mutStr insertAttributedString:attachStr1 atIndex:50*i];
}
_lab_AAAA.attributedText = [mutStr copy];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
效果圖如下:

感謝學習,學以緻用更感謝~