Analyze the problems encountered in the text-and-text mixing of Weibo editing pages, and analyze the text-and-Text

Source: Internet
Author: User

Analyze the problems encountered in the text-and-text mixing of Weibo editing pages, and analyze the text-and-Text

There are many details in the text-and-text mix of the emoticon keyboard. Sometimes it is difficult to correct the cause. This article focuses on the various problems and solutions I have encountered for your sharing. If you have encountered similar problems before, you can use my methods to correct them. I hope they will help you. In this article, the swift language is used, and OC may not be used to it, but most of the methods are basically the same, that is, the syntax is different.

Last Review: Add emoticon keyboard on Weibo editing page

If you did not see this article in Dong Boran's blog, click to view the original article.

1. By default, each added expression is added to the end, but we want to add it to the cursor position.

Default practice (str is an emoticon string sent by clicking an emoticon proxy)

// The user-selected expression is spliced to the end! TextView. text = textView. text + (str ?? "")!

If you want to insert to the cursor position

// Insert textView. replaceRange (textView. selectedTextRange !, WithText: str !)
2. The size of the added icon is different.

Solution: set a uniform format for all the ranges.

// Set the text attribute let range = NSMakeRange (0, strM. length) in the entire property string // make the font of the variable property text consistent with that of the textView! StrM. addattriename (NSFontAttributeName, value: textView. font, range: range)

 

3. Because the text is replaced, the cursor will jump to the end of the paragraph after the expression is inserted in the middle.

Solution: record the cursor position in advance and restore the cursor position after the text position is replaced.

When the cursor is restored, it should be location + 1. If 1 is not added, the cursor is inserted before the expression.

// Record the location of the cursor corresponding to the position of the cursor var location = textView. selectedRange. location // directly replacing the text result will cause the cursor to move to the textView at the end of the text. attributedText = strM // reset the cursor position textView. selectedRange = NSMakeRange (location + 1, 0)

 

4. However, textView. AttrubuteText is displayed in textView. Fuwen is an object that cannot be directly sent out.

Solution:

① Print textView. AttrubuteText each time you click on the emoticons to see a large number of prints. The output is a dictionary. After differentiation, we can see that if it is an expression, there is a NSAttachment key value in the dictionary. The text does not

② Based on the difference above, traverse the large number of prints, print the dict and Range, and separate all the texts and expressions.

Print:

③ Use this idea to write a subclass of textAttrubute and assign values to the text symbols corresponding to the emoticon in this method.

Import UIKitclass SXEmoteTextAttachment: NSTextAttachment {// text symbol var emoteString: String? /// Return an attribute string class func attributeString (emoticon: Emoticon, height: CGFloat)-> NSAttributedString {var attachment = SXEmoteTextAttachment () attachment. image = UIImage (contentsOfFile: emoticon. imagePath !) Attachment. emoteString = emoticon. chs // set the height of attachment. bounds = CGRectMake (0,-4, height, height) // 2. attribute text with image return NSAttributedString (attachment: attachment )}}

④ When you click an image, a property string is returned by calling the method. The expression is automatically converted to a text symbol when you call attributeString.

        var attributeString = SXEmoteTextAttachment.attributeString(emoticon, height: font.lineHeight)

⑤ Define a result to record the concatenated string

/// Return the converted String in the text box-(convert an emoticon image to an emoticon) func fullText ()-> String {var result = String () let textRange = NSMakeRange (0, attributedText. length) attributedText. enumerateAttributesInRange (textRange, options: NSAttributedStringEnumerationOptions. allZeros, usingBlock: {(dict, range, _)-> Void in if let attachment = dict ["NSAttachment"]? SXEmoteTextAttachment {// picture result + = attachment. emoteString! } Else {result + = (self. attributedText. string as NSString). substringWithRange (range) }}) println ("Weibo text: \ (result)") return result}

6. Finally, modify the parameters when posting Weibo messages, either by sending textView. AttrubuteText or by sending textView. text.

// Send Weibo @ IBAction func sendStatus (sender: UIBarButtonItem) {let urlString = "https://api.weibo.com/2/statuses/update.json" if let token = AccessToken. loadAccessToken ()?. Access_token {// here the fullText method is called to return the record and the merged let params = ["access_token": token, "status": textView. fullText ()] let net = NetworkManager. sharedManager net. requestJSON (. POST, urlString, params) {(result, error)-> () in SVProgressHUD. showInfoWithStatus ("Weibo sent successfully") self. dismissViewControllerAnimated (true, completion: nil )}}}

7. This completes. editing the display in Weibo is separated from the text sent when Weibo is sent and does not conflict with each other.

 

5. When the release is canceled, the Weibo controller will be quickly scaled back, And the keyboard will be scaled back slowly after it is returned to the home page.

Solution:

/// Click the cancel button to click the event @ IBAction func cancel (sender: UIBarButtonItem) {// for better user experience, first shrink the keyboard and then the text box self. textView. resignFirstResponder () dismissViewControllerAnimated (true, completion: nil )}

 

6. In the input box, the emoticon and text are not aligned horizontally, and there is a difference between the upper and lower sides.

Solution: fine-tune

            let height = textView.font.lineHeight            attachment.bounds = CGRectMake(0, -4, height, height)

 

7. The placeholder and send buttons are hidden and lit only when the text is entered. No response is returned when you click to insert an image.

Solution: manually ask the user to call the proxy method when entering the image

In the image clicking proxy method emoticonsViewControllerDidSelectEmoticon

// Manually call the proxy method-whether the text can be inserted if textView (textView, shouldChangeTextInRange: textView. selectedRange, replacementText: str !) {// Set the text in the input box if emoticon. chs! = Nil {// retrieve textView. setTextEmoticon (emoticon) from the classification method // manually call the didChage method textViewDidChange (textView)} else if emoticon. emoji! = Nil {// by default, the expression is spliced to the end. With this line of code, the text textView. replaceRange (textView. selectedTextRange !, WithText: emoticon. emoji !) }}

TextViewDidChange is used to control the button status.

    func textViewDidChange(textView: UITextView) {        let fullText = self.textView.fullText()                self.textView.placeHolderLabel!.hidden = !fullText.isEmpty        sendButton.enabled = !fullText.isEmpty    }

 

 

8. When controlling the maximum number of inputs, an expression such as "[flowers]" occupies 8 bytes.

It turns out to be

// Weibo text is usually limited to 140 words if textView. text. lengthOfBytesUsingEncoding (NSUTF8StringEncoding) + text. lengthOfBytesUsingEncoding (NSUTF8StringEncoding)> 140 {return false}

Change

// Weibo text is usually limited to 140 words if (self. textView. fullText () as NSString). length + (text as NSString). length> 140 {return false}

 

If you did not see this article in Dong Boran's blog, click to view the original article.

Welcome!

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.