iOS2017 (NSString和NSAttributedString)相互轉換

鑒于很多人瀏覽過本文,為了不讓之前糟糕的格式浪費大家寶貴的時間我重新寫了一篇更新版,親們還是移步那篇把.

? ? ? 最近研究了含表情的字符串,我們實現(xiàn)像??的其實不難??,輸入法都支持??,但是如果想換成自己需要的圖片表情,甚至GIF動畫表情,就要花一番功夫了????????。

除了利用webview寫HTML的方法外,有一種更加清明的方法,那就是屬性字符串,即NSAttributedString、NSMutableAttributedString,顧名思義后者就是可變的而已。

首先,先實現(xiàn)普通字符串轉屬性字符串吧(網(wǎng)上現(xiàn)成的??):

+(NSMutableAttributedString *)stringToAttributeString:(NSString *)text

{

//先把普通的字符串text轉化生成Attributed類型的字符串

NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc]initWithString:text];

NSString * zhengze = @"\\[\\([a-zA-Z0-9\u4e00-\u9fa5]+\\)\\]"; //正則表達式 ,例如? [(呵呵)] = ??

NSError * error;

NSRegularExpression * re = [NSRegularExpression regularExpressionWithPattern:zhengze options:NSRegularExpressionCaseInsensitive error:&error];

if (!re)

{

NSLog(@"%@??",[error localizedDescription]);//打印錯誤??

}

NSArray * arr = [re matchesInString:text options:0 range:NSMakeRange(0, text.length)];//遍歷字符串,獲得所有的匹配字符串

NSBundle *bundle = [NSBundle mainBundle];

NSString * path = [bundle pathForResource:@"emj" ofType:@"plist"];? //plist文件,制作一個 數(shù)組,包含文字,表情圖片名稱

NSArray * face = [[NSArray alloc]initWithContentsOfFile:path];//獲取 所有的數(shù)組

//如果有多個表情圖,必須從后往前替換,因為替換后Range就不準確了

for (int j =(int) arr.count - 1; j >= 0; j--) {

//NSTextCheckingResult里面包含range

NSTextCheckingResult * result = arr[j];

for (int i = 0; i < face.count; i++) {

if ([[text substringWithRange:result.range] isEqualToString:face[i][@"key"]])//從數(shù)組中的字典中取元素

{

NSString * imageName = [NSString stringWithString:face[i][@"picture"]];

NSTextAttachment * textAttachment = [[NSTextAttachment alloc]init];//添加附件,圖片

//textAttachment.bounds=CGRectMake(0, 0, 20, 20);//調節(jié)表情大小

textAttachment.image = [UIImage imageNamed:imageName];

NSAttributedString * imageStr = [NSAttributedString attributedStringWithAttachment:textAttachment];

[attStr replaceCharactersInRange:result.range withAttributedString:imageStr];//替換未圖片附件

break;

}

}

}

return attStr;

}

//==============??=======================

當然,你肯定會需要轉回來??:

//把帶有圖片的屬性字符串轉成普通的字符串

+ (NSString *)textString:(NSAttributedString *)attributedText

{

NSMutableAttributedString * resutlAtt = [[NSMutableAttributedString alloc]initWithAttributedString:attributedText];

EmoticonsHelper * helper = [EmoticonsHelper new];

//枚舉出所有的附件字符串

[attributedText enumerateAttributesInRange:NSMakeRange(0, attributedText.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {

NSTextAttachment * textAtt = attrs[@"NSAttachment"];//從字典中取得那一個圖片

if (textAtt)

{

UIImage * image = textAtt.image;

NSString * text = [helper stringFromImage:image];

[resutlAtt replaceCharactersInRange:range withString:text];

}

}];

return resutlAtt.string;

}

//獲取圖片數(shù)組

-(NSArray *)getAllImagePaths//數(shù)組結構還是上述的截圖的數(shù)組結構

{

NSBundle *bundle = [NSBundle mainBundle];

NSString * path = [bundle pathForResource:@"emojo" ofType:@"plist"];

NSArray * face = [[NSArray alloc]initWithContentsOfFile:path];

return face;

}

//=================================

會不會需要屬性字符串的尺寸大小呢?不用著急,直接有代碼:

+(CGSize)getAttributedTextSize:(NSString *)text

{

//先把普通的字符串text轉化生成Attributed類型的字符串

NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc]initWithString:text];

NSString * zhengze = @"\\[\\([a-zA-Z0-9\u4e00-\u9fa5]+\\)\\]";

NSError * error;

NSRegularExpression * re = [NSRegularExpression regularExpressionWithPattern:zhengze options:NSRegularExpressionCaseInsensitive error:&error];

if (!re)

{

NSLog(@"正則表達式匹配錯誤%@" ,[error localizedDescription]);

}

NSArray * arr = [re matchesInString:text options:0 range:NSMakeRange(0, text.length)];

if (!arr.count)//說明字符串中沒有表情通配符,是普通的文本,則計算文本size

{

NSDictionary *dic=@{NSFontAttributeName: [UIFont systemFontOfSize:14]};

CGSize size1=[text boundingRectWithSize:CGSizeMake(160, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;

if (size1.height<=60)

{

size1.height=60;

}

else

{

size1.height+=15;

}

return size1;

}

NSBundle *bundle = [NSBundle mainBundle];

NSString * path = [bundle pathForResource:@"emj" ofType:@"plist"];

NSArray * face = [[NSArray alloc]initWithContentsOfFile:path];

//如果有多個表情圖,必須從后往前替換,因為替換后Range就不準確了

for (int j =(int) arr.count - 1; j >= 0; j--) {

//NSTextCheckingResult里面包含range

NSTextCheckingResult * result = arr[j];

for (int i = 0; i < face.count; i++) {

if ([[text substringWithRange:result.range] isEqualToString:face[i][@"key"]])

{

NSString * imageName = [NSString stringWithString:face[i][@"picture"]];

NSTextAttachment * textAttachment = [[NSTextAttachment alloc]init];

textAttachment.image = [UIImage imageNamed:imageName];

NSAttributedString * imageStr = [NSAttributedString attributedStringWithAttachment:textAttachment];

[attStr replaceCharactersInRange:result.range withAttributedString:imageStr];

break;

}

}

}

CGSize size2=[attStr boundingRectWithSize:CGSizeMake(180, 1000) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;

size2.height+=40;? //表情文字增加高度

return size2;//返回屬性字符串的尺寸

}

//==================================================

當然,以上這些都是網(wǎng)上現(xiàn)成的??,下面要寫一點不一樣的東西了??????????????????????????????????????????????

???????? 首先我們知道和字符串相關的UI控件呢不外乎那么幾種,怎么樣利用上屬性字符串呢???

1、UITextView、UITextField

以UITextView為例,假設你得到的屬性字符串是NSAttributedString *result,我要顯示出表情圖片還得:

[TextView.textStorage insertAttributedString:result TextView.selectedRange.location];

TextView.selectedRange = NSMakeRange(TextView.selectedRange.location+1, 0);

//重置格式

NSRange wholeRange = NSMakeRange(0,TextView.textStorage.length);

[TextView.textStorage removeAttribute:NSFontAttributeName range:wholeRange];

[TextView.textStorage addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0f] range:wholeRange];

這樣不但能顯示表情圖片到你的TextView里??,還能通過UIFont
設置顯示的大小。

2、UILabel

這個控件就不用多說了,直接有個屬性名字叫attributedText,設上result
就能顯示了。

本文就到此結束了??????????。。。。。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,197評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,415評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 176,104評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,884評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,647評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,130評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,208評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,366評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,887評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,737評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,939評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,478評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,174評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,586評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,827評論 1 283
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,608評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,914評論 2 372

推薦閱讀更多精彩內容