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代码:

@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.在你的代码里面加入:



NSMutableAttributedString 

* string = [[ 

NSMutableAttributedStringalloc 

] initWithString:@"123456789101112"  attributes:nil


] ;




 MMTextAttachment

* textAttachment = [[ MMTextAttachment alloc ]

initWithData:nil


ofType:nil


] ;

 


    UIImage

* smileImage = [ UIImage imageNamed:@"a.jpg"


]  ;  //my

emoticon image named a.jpg

 


    textAttachment.image

= smileImage ;

 


    NSAttributedString


* textAttachmentString = [ 

NSAttributedString 

attributedStringWithAttachment:textAttachment ] ;

 


    [

string insertAttributedString:textAttachmentString atIndex:6 ]

;

 


    _textView.attributedText

= string ;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值