用textkit實現圖文混排

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代碼:
  1. @interface MMTextAttachment : NSTextAttachment


  2. @end
  3. @implementation MMTextAttachment 
  4. //I want my emoticon has the same size with line's height 
  5. - (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex NS_AVAILABLE_IOS(7_0) 

  6. return CGRectMake( 0 , 0 , lineFrag.size.height , lineFrag.size.height ); 

  7. @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 ;
複製代碼

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

原文鏈接:http://www.cocoachina.com/bbs/read.php?tid=144272&fpage=14
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章