iOS圖文混排與NSString轉(zhuǎn)換

圖文混排是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)單的文本編輯器。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容