iOS Development display Weibo emoticons

Source: Internet
Author: User

In the previous blog in the cottage of Sina Weibo, in the following blog will be on the previous code optimization and reuse, the text of the previous microblogging request has not been processed, such as with the expression of the text is such a "I Want to [laugh],[proud]". The requested string is displayed, so how do we change the text locally to the expression? Here's a look at the solution that shows the emoticons.

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:

    // Loading Data    from a plist file NSBundle *bundle = [NSBundle mainbundle];     // find the path    to the resource NSString *path = [Bundle Pathforresource:@ "emoticons" ofType:@ "plist "];     // get the data    in plist Nsarray *face = [[Nsarray alloc] initwithcontentsoffile:path];

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

    // the string we want to display (the string format of the analog network request)    @" I [watching] 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:

   // to 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 of text to replace//Regular ExpressionsNSString * 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 expressionsNsarray *resultarray = [Re matchesinstring:str options:0Range: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 dictionaries, where images and images are stored in a dictionary.2Nsmutablearray *imagearray =[Nsmutablearray ArrayWithCapacity:resultArray.count];3     4     //Replace the image with the corresponding range5      for(Nstextcheckingresult *matchinchresultarray) {6         //gets the array element to get the range7Nsrange range =[Match Range];8         9         //gets the corresponding value in the original stringTenNSString *substr =[str substringwithrange:range]; One          A          for(inti =0; i < Face.count; i + +) -         { -             if([face[i][@"CHS"] isequaltostring:substr]) the             { -                  -                 //face[i][@ "gif" is the picture we want to load -                 //Create a new text attachment to store our pictures +Nstextattachment *textattachment =[[Nstextattachment alloc] init]; -                +                 //add a picture to an attachment ATextattachment.image = [UIImage imagenamed:face[i][@"PNG"]]; at                  -                 //converts an attachment to a mutable string to replace the emoticon text in the source string -Nsattributedstring *imagestr =[nsattributedstring attributedstringwithattachment:textattachment]; -                  -                 //Place pictures and pictures in a dictionary -Nsmutabledictionary *imagedic = [Nsmutabledictionary dictionarywithcapacity:2]; in[Imagedic setobject:imagestr Forkey:@"Image"]; -[Imagedic setobject:[nsvalue Valuewithrange:range] Forkey:@"Range"]; to                  +                 //put the dictionary into an array - [Imagearray addobject:imagedic]; the                  *             } $         }Panax Notoginseng}

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 from back to forward2      for(inti = Imagearray.count-1; I >=0; i--)3     {4 Nsrange Range;5[imagearray[i][@"Range"] getvalue:&Range];6         //to replace7[AttributeString Replacecharactersinrange:range withattributedstring:imagearray[i][@"Image"]];8         9}

8. Assign the replaced variable attribute string to the TextView

1     // assign the value of the replacement to our TextView 2     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.