圖文混排是iOS開發(fā)中經(jīng)常遇到的一個(gè)場(chǎng)景,網(wǎng)上的教程往往只說明了如何將一篇圖文混合的內(nèi)容展示出來,而忽略了將一篇圖文混合的內(nèi)容翻譯為約定的數(shù)據(jù),從而進(jìn)行存儲(chǔ)和傳輸使用。
iOS7.0之后可以使用NSTextAttachment與NSAttributedString完成圖文混排的展示
- (NSAttributedString*)attributedStringWithImage:(UIImage*)image
{
NSTextAttachment*attch = [[NSTextAttachment alloc]init];
attch.image= image;
attch.bounds=CGRectMake(0,0,32,32);//設(shè)置圖片大小
return [NSAttributedString attributedStringWithAttachment:attch];
}
完成了圖文混排的展示后,需要將混排的內(nèi)容轉(zhuǎn)換成String使用
- (NSString *)stringFromAttributedString:(NSAttributedString *)attr
{
NSMutableAttributedString * resutlAtt = [[NSMutableAttributedString alloc]initWithAttributedString:attr];
// 這個(gè)方法是文本結(jié)尾開始向前列舉,可以放心使用replace方法而不用擔(dān)心替換后range發(fā)生變化導(dǎo)致問題
[attr enumerateAttributesInRange:NSMakeRange(0, attr.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
NSTextAttachment * textAtt = attrs[@"NSAttachment"]; // 從字典中取得那一個(gè)圖片
if (textAtt)
{
UIImage * image = textAtt.image;
[resutlAtt replaceCharactersInRange:range withString:[self stringWithImage:image]];
}
}];
return resutlAtt.string;
}
- (NSString *)stringWithImage:(UIImage *)image
{
NSString *result = @"";
/**
* 將圖片翻譯成你所需要的內(nèi)容
**/
return result;
}
通過列舉NSAttributedString中的內(nèi)容,并對(duì)其中特定的內(nèi)容進(jìn)行轉(zhuǎn)換的方法,不只可以用于對(duì)圖片內(nèi)容的轉(zhuǎn)換,可以基于這個(gè)思路完成一個(gè)簡(jiǎn)單的文本編輯器。