用TextKit實現表情混排

來源:互聯網
上載者:User

標籤:

原文 : http://www.cocoachina.com/bbs/read.php?tid=144272&fpage=14

Textkit是iOS7新推出的類庫,其實是在之前推出的CoreText上的封裝,有了這個TextKit,以後不用再拿著CoreText來做累活了,根據蘋果的說法,他們開發了兩年多才完成,而且他們在開發時候也將表情混排作為一個使用案例進行研究,所以要實現表情混排將會非常容易。 TextKit並沒有新增的類,他是在原有的文本顯示控制項上的封裝,可以使用平時我們最喜歡使用的UILabel,UITextField,UITextView裡面就可以使用了。

1.NSAtrributedString
這是所有TextKit的載體,所有的資訊都會輸入到NSAttributedString裡面,然後將這個String輸入到Text控制項裡面就可以顯示了。

2.NSTextAttachment
iOS7新增的類,作為文本的附件,可以放檔案,可以放資料,以 NSAttachmentAttributeName這個key放入NSAttributedString裡面,在表情混排這裡,我們將放入image。

3.重載NSTextAttachment
本來是可以直接使用NSTextAttachment,但是我們需要根據文字大小來改變表情圖片的大小,於是我們需要重載NSTextAttachment,NSTextAttachment實現了NSTextAttachmentContainer,可以給我們改變返回的映像,映像的大小。
重載NSTextAttachment代碼:

@interface MMTextAttachment : NSTextAttachment{ } @end@implementation MMTextAttachment //I want my emoticon has the same size with line‘s height - (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex NS_AVAILABLE_IOS(7_0) { return CGRectMake( 0 , 0 , lineFrag.size.height , lineFrag.size.height ); } @end

4.在你的代碼裡面加入:

1 NSMutableAttributedString * string = [[ NSMutableAttributedStringalloc ] initWithString:@"123456789101112" attributes:nil ] ; 2 MMTextAttachment * textAttachment = [[ MMTextAttachment alloc ] initWithData:nil ofType:nil ] ; 3 UIImage * smileImage = [ UIImage imageNamed:@"a.jpg" ] ; //my emoticon image named a.jpg 4 textAttachment.image = smileImage ; 5 NSAttributedString * textAttachmentString = [ NSAttributedString attributedStringWithAttachment:textAttachment ] ; 6 [ string insertAttributedString:textAttachmentString atIndex:6 ] ; 7 _textView.attributedText = string ;

最後,最厲害的一點是,從此以後,可以在輸入的同時也可以編輯圖片了。

  

用TextKit實現表情混排

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.