iOS Development property String nsattributestring and NSString convert to include picture

Source: Internet
Author: User

Share several commonly used property strings nsatrributestring and NSString Ordinary string conversion methods:

One: Replace the normal string with the property string containing the picture

plist file, picture format see:


+ (nsmutableattributedstring *) stringtoattributestring: (NSString *) text{    //First convert normal string text to generate attributed type string    nsmutableattributedstring * attstr = [[nsmutableattributedstring alloc]initwithstring:text];        NSString * Zhengze = @ "\\[[a-za-z0-9\\u4e00-\\u9fa5]+\\]"; Regular expressions, such as  [hehe] This form of wildcard character        Nserror * ERROR;
<span style= "font-family:arial, Helvetica, Sans-serif;" > nsregularexpression * re = [nsregularexpression regularexpressionwithpattern:zhengze options: Nsregularexpressioncaseinsensitive error:&error];//Regular expression </span> 
    if (!re) {NSLog (@ "%@", [Error localizeddescription]);//Print Error} Nsarray * arr = [Re matchesinstring:    Text options:0 range:nsmakerange (0, Text.length)];//traverse the string to get all the matching strings nsbundle *bundle = [NSBundle mainbundle];  NSString * Path = [bundle pathforresource:@ "Emotions" oftype:@ "plist"];  plist file, make an array containing text, emoji image name nsarray * face = [[Nsarray Alloc]initwithcontentsoffile:path]; Get all arrays//If there are multiple emoticons, it must be replaced from the back, since the range is inaccurate for (int j = (int) arr.count-1; j >= 0; j--) {//nstex                Tcheckingresult contains range Nstextcheckingresult * result = Arr[j]; for (int i = 0; i < Face.count; i++) {if ([[[Text SubstringWithRange:result.range] isequaltostring:face[i][@                                "CHS"])//From the dictionary in the array to take the element {NSString * imageName = [nsstring stringwithstring:face[i][@ "PNG"]];                              Nstextattachment * textattachment = [[nstextattachment alloc]init];//add attachment, picture  Textattachment.image = [UIImage imagenamed:imagename];                                nsattributedstring * Imagestr = [nsattributedstring attributedstringwithattachment:textattachment];                                [Attstr replaceCharactersInRange:result.range withattributedstring:imagestr];//Replace picture attachment            Break }}} return attstr;}

Two: Gets the size of the property string:

Note: For property strings that contain text and pictures, you need to adjust their size according to the actual situation.

+ (Cgsize) getattributedtextsize: (NSString *) text{//First convert normal string text to generate attributed type of string nsmutableattributedstring * att        STR = [[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 (@ "Regular expression matches error%@", [Error localizeddescription]);            } Nsarray * arr = [Re matchesinstring:text options:0 range:nsmakerange (0, text.length)]; if (!arr.count)//Description string does not have expression wildcard, is plain text, then calculate text size {nsdictionary *[email protected]{nsfontattributename: [UIF                        Ont systemfontofsize:14]}; Cgsize size1=[text Boundingrectwithsize:cgsizemake (+) 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:@ "Emotions" oftype:@ "plist"];        Nsarray * face = [[Nsarray Alloc]initwithcontentsoffile:path]; If you have more than one emoticon, you must replace it from the back, since the range is inaccurate for (int j = (int) arr.count-1; j >= 0; j--) {//nstextcheckingresult bread                Contains range Nstextcheckingresult * result = Arr[j]; for (int i = 0; i < Face.count; i++) {if ([[[Text SubstringWithRange:result.range] isequaltostring:face[i][@                                "CHS"]) {NSString * imageName = [nsstring stringwithstring:face[i][@ "PNG"]];                                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 (+) Options:nsstringdrawinguseslinefrag        Mentorigin context:nil].size;  size2.height+=40; Emoji Add height return size2;//returns the dimension of the property string}

Three: attribute string to normal string, key point: Picture binary alignment (can be put into a sub-thread to do)

Picture binary alignment, get picture name:

Can't get the string name directly?-(NSString *) Stringfromimage: (UIImage *) image{    nsarray *face=[self getallimagepaths];        NSData * imaged = uiimagepngrepresentation (image);        NSString * IMAGENAME;        for (int i=0; i<face.count; i++)    {        UIImage *image=[uiimage imagenamed:face[i][@ "PNG"]];        NSData *data=uiimagepngrepresentation (image);        if ([imaged isequaltodata:data])        {            imagename=face[i][@ "CHS"];            NSLog (@ "match succeeded!");        }    }            return imageName;} -(Nsarray *) getallimagepaths//array structure or the above array structure {    nsbundle *bundle = [NSBundle mainbundle];        NSString * Path = [bundle pathforresource:@ "Emotions" oftype:@ "plist"];        Nsarray * face = [[Nsarray alloc]initwithcontentsoffile:path];        return face;}
The property string is converted to a normal string:

Assuming that Textview,label,button is the same

Turn the property string with the picture into a normal string-(NSString *) textstring{    nsattributedstring * att = self.attributedtext;        nsmutableattributedstring * Resutlatt = [[nsmutableattributedstring Alloc]initwithattributedstring:att];            __weak __block Uitextview * copy_self = self;    Enumerate all the attachment strings    [att enumerateattributesinrange:nsmakerange (0, att.length) options: Nsattributedstringenumerationreverse usingblock:^ (nsdictionary *attrs, Nsrange range, BOOL *stop) {        // Key-nsattachment        //nstextattachment value type        nstextattachment * Textatt = attrs[@ "Nsattachment"];// Get that picture from the dictionary        if (textatt)        {            UIImage * image = Textatt.image;            NSString * Text = [copy_self stringfromimage:image];            [Resutlatt Replacecharactersinrange:range withstring:text];                    }                    ];            return resutlatt.string;}

Original address: http://blog.csdn.net/yangbingbinga/



iOS Development property String nsattributestring and NSString convert to include picture

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.