The property string NSAttributeString and NSString of ios development are converted to each other and contain images.

Source: Internet
Author: User

The property string NSAttributeString and NSString of ios development are converted to each other and contain images.

The following describes how to convert common attribute strings NSAtrributeString and NSString:

 

 

1. Replace a common string with an attribute string containing the image.

Plist file. For the image format, see:

+ (Optional *) stringToAttributeString :( NSString *) text {// convert the common string text to generate the Attributed String NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc] initWithString: text]; NSString * zhengze = @ \ [[a-zA-Z0-9 \ u4e00-\ u9fa5] + \]; // regular expression, such as [Haha] This form of wildcard NSError * error;
NSRegularExpression * re = [NSRegularExpression regularExpressionWithPattern: zhengze options: NSRegularExpressionCaseInsensitive error: & error]; // Regular Expression
If (! Re) {NSLog (@ % @, [error localizedDescription]); // print error} NSArray * arr = [re matchesInString: text options: 0 range: NSMakeRange (0, text. length)]; // traverses the string to obtain all matching strings NSBundle * bundle = [NSBundle mainBundle]; NSString * path = [bundle pathForResource: @ emotions ofType: @ plist]; // plist file, create an array containing text, emoticon image name NSArray * face = [[NSArray alloc] initWithContentsOfFile: path]; // obtain all arrays // If there are multiple emoticon, it must be replaced from the back to the front, because the Range after replacement is inaccurate for (int j = (int) arr. count-1; j> = 0; j --) {// The NSTextCheckingResult contains range NSTextCheckingResult * result = arr [j]; for (int I = 0; I <face. count; I ++) {if ([[text substringWithRange: result. range] isEqualToString: face [I] [@ chs]) // retrieves the element {NSString * imageName = [NSString stringWithString from the dictionary in the array: face [I] [@ png]; NSTextAttachment * textAttachment = [[NSTextAttachment alloc] init]; // Add an attachment to the image textAttachment. image = [UIImage imageNamed: imageName]; NSAttributedString * imageStr = [NSAttributedString attributedStringWithAttachment: textAttachment]; [attStr replaceCharactersInRange: result. range withAttributedString: imageStr]; // replace break without image attachments; }}return attStr ;}

2. Get the size of the attribute string:

Note: adjust the size of attribute strings that contain text and images based on actual conditions.

 

+ (CGSize) getAttributedTextSize :( NSString *) text {// convert the common string text to generate the Attributed String NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc] initWithString: text]; NSString * zhengze = @ \ [[a-zA-Z0-9 \ u4e00-\ u9fa5] + \]; NSError * error; NSRegularExpression * re = [NSRegularExpression regularExpressionWithPattern: zhengze options: Unknown error: & error]; if (! Re) {NSLog (@ regular expression matching error % @, [error localizedDescription]);} NSArray * arr = [re matchesInString: text options: 0 range: NSMakeRange (0, text. length)]; if (! Arr. count) // If the string contains no expression wildcard characters and is a common text, the calculated text size {NSDictionary * dic =@{ NSFontAttributeName: [UIFont systemFontOfSize: 14]}; CGSize size1 = [text boundingRectWithSize: CGSizeMake (160,100 0) 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 multiple emojis exist, it must be replaced from the back to the front, because the Range after replacement is not accurate for (int j = (int) arr. count-1; j> = 0; j --) {// The NSTextCheckingResult 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 (180,100 0) options: NSStringDrawingUsesLineFragmentOrigin context: nil]. size; size2.height + = 40; // The height of return size2 is increased for emoticon; // the size of the returned attribute string}

3. Convert the attribute string to a normal string. Key Point: Binary comparison of the image (which can be done in a subthread)

 

Image Binary comparison to obtain the image name:

 

// The Name Of The string cannot be obtained directly? -(NSString *) stringFromImage :( UIImage *) image {NSArray * face = [self getAllImagePaths]; NSData * imageD = UIImagePNGRepresentation (image); NSString * imageName; for (int I = 0; I
 
  
Convert an attribute string to a normal string:
  

 

Assume TextView, label, and button are the same.

 

// Convert an attribute string with an image to a normal string-(NSString *) textString {NSAttributedString * att = self. attributedText; NSMutableAttributedString * resutlAtt = [[NSMutableAttributedString alloc] identifier: att]; _ weak _ block UITextView * copy_self = self; // lists all the attachment strings [att tags: NSMakeRange (0, att. length) options: NSAttributedStringEnumerationReverse usingBlock: ^ (NSDictionary * attrs, nsange range, BOOL * stop) {// key-NSAttachment // NSTextAttachment value Type NSTextAttachment * textAtt = attrs [@ NSAttachment]; // obtain the image from the dictionary if (textAtt) {UIImage * image = textAtt. image; NSString * text = [copy_self stringFromImage: image]; [resutlAtt replaceCharactersInRange: range withString: text] ;}]; return resutlAtt. string ;}

 

 

 

Related Article

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.