iOS Development display Weibo emoticons

Source: Internet
Author: User

Knowledge to use: Resource files in iOS development. plist, variable property strings, TextView, and regular expressions.

Solution of the overall idea: the source string with the regular match to get to each expression range, and then through range to get the expression string in the meta-string, such as [haha], in the [haha] Match the CHS field under item in our. plist, then get the corresponding picture name, get the picture and convert the image to a mutable string attachment, and then make a replacement. First of all, the following will be explained in detail below.

1. In order to display the expression of the network request on our mobile phone, we must first have the corresponding resource file locally, In the. plist file again we want something that stores something like this, the whole root is an array, the item in the array is a dictionary, a map of the text to the image name in the dictionary, of course, the picture name is the same as the picture name of our local resource. As follows

2. How do I get data from a. plist file? First, through the bundle to get the path of the resource file, in the file path to create an array, the data stored in the array is the file content code is as follows:

    Load the data in the plist file    nsbundle *bundle = [NSBundle mainbundle];    Find the path to the resource    nsstring *path = [Bundle pathforresource:@ "Emoticons" oftype:@ "plist"];    Get data in plist    nsarray *face = [[Nsarray alloc] initwithcontentsoffile:path];

3. Generate our test string, the last one is not any expression, do not replace.

    We want to display the string (the string format of the analog network request)    NSString *str = @ "I [onlookers] you [mighty] You [Hee] I [Love you] you [rabbit] I [cool] you [handsome] I [think] you [money][123456]";

4. Convert the above str to a mutable property string, because we want to display our emoji image on TextView with a mutable property string, the conversion code is as follows:

   Create a mutable property string    nsmutableattributedstring *attributestring = [[Nsmutableattributedstring alloc] initwithstring: STR];

5. Make a regular match, get the range of each expression in the string, the following regular expression will match [/*], so [123567] will also be matched, below we will do the corresponding processing

  Regular matches the range//regular expression of the text to be replaced    NSString * pattern = @ "\\[[a-za-z0-9\\u4e00-\\u9fa5]+\\]";    Nserror *error = nil;    Nsregularexpression * re = [nsregularexpression regularexpressionwithpattern:pattern options: Nsregularexpressioncaseinsensitive error:&error];        if (!re) {        NSLog (@ "%@", [Error localizeddescription]);    }        Match strings with regular expressions    nsarray *resultarray = [Re matchesinstring:str options:0 range:nsmakerange (0, str.length)];

6. Data preparation work is completed, the following begins to traverse the resource file to find the text corresponding to the picture, find the picture name in the dictionary, the picture in the source string position also to be stored in the dictionary, and finally put the dictionary into a variable array. The code is as follows:

 1//used to store the dictionary, the dictionary is stored in the picture and picture corresponding to the location 2 nsmutablearray *imagearray = [Nsmutablearray arrayWithCapacity:resultArray.count];         3 4//Match range to replace the image with a corresponding 5 for (Nstextcheckingresult *match in resultarray) {6//get array element get range 7 Nsrange range = [Match range]; 8 9//Gets the corresponding value in the original string nsstring *substr = [Str substringwithrange:range];11 int i = 0; i < Face.count;                 i + +) ([face[i][@ "CHS"] isequaltostring:substr]) 15 {16 17  face[i][@ "GIF" is the image we want to load 18//New text attachment to store our picture nstextattachment *textattachment = [[Nstextattachment alloc] init];20 21//Add a picture to the attachment Textattachment.image =                 [UIImage imagenamed:face[i][@ "PNG"]];23 24//Convert attachment to variable string to replace emoji in source string 25 nsattributedstring *imagestr = [nsattributedstring AttributedstringwithattachmeNt:textattachment];26 27//Place the picture and picture in the dictionary nsmutabledictionary *imagedi                 c = [Nsmutabledictionary dictionarywithcapacity:2];29 [imagedic setobject:imagestr forkey:@ "image"];30 [Imagedic setobject:[nsvalue Valuewithrange:range] forkey:@ "range"];31 32// Dictionary stored in array [imagearray addobject:imagedic];34 35}36}37}

7. The conversion is done, we need to replace the attributestring, replace the back and forth, the weak from the previous replacement, will cause the range and the picture to put the position mismatch problem. The replacement code is as follows:

1     //replace 2 for     (int i = imagearray.count-1; I >= 0; i--) 3     {4         nsrange range;5         [imagearray[i][@] from backward forward Range "] getvalue:&range];6         //Replace 7         [AttributeString Replacecharactersinrange:range withattributedstring:imagearray[i][@ "image"]];8         9     }

8. Assign the replaced variable attribute string to the TextView

1     //Assign the replacement value to our TextView2     self.myTextView.attributedText = attributestring;

9. Before and after the replacement effect is as follows:

iOS Development display Weibo emoticons

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.