標籤:
原文 : 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實現表情混排