How to wrap text around attachments using iOS7 Text Kit?

假如想象 提交于 2019-12-02 17:38:13

NSTextAttachments are treated as a single character by NSAttributedString. So, in order to adjust their alignment you must do so as you would for text. It took me hours of fiddling with attachment.bounds (which I never could get to work properly) to finally figure this out. Here's an example of how to horizontally align an NSTextAttachment.

#def BETWEEN_SECTION_SPACING 10  

// creates a text attachment with an image

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];

attachment.image = [UIImage imageNamed:@"sample_image.jpg"];

NSMutableAttributedString *imageAttrString = [[NSAttributedString attributedStringWithAttachment:attachment] mutableCopy];



// sets the paragraph styling of the text attachment

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init] ;

[paragraphStyle setAlignment:NSTextAlignmentCenter];            // centers image horizontally

[paragraphStyle setParagraphSpacing:BETWEEN_SECTION_SPACING];   // adds some padding between the image and the following section

[imageAttrString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [imageAttrString length])];

After this, you would append imageAttrString to an existing attributed string and perhaps append another after it. One quirk is that because the attachment is a character it is not treated as its own paragraph. In order for that to be the case you will need to surround it with \n (newline characters). Just append these to both sides of the attachment's attributed string.

Hope that helps, it took me ages to figure out.

Try setting the bounds property to the image size.

Defines the layout bounds of the receiver's graphical representation in the text coordinate system.

So it should be:

ta.bounds = (CGRect) { 0, 0, ta.image.size };
ta.bounds = (CGRect) { 0, yPadding, ta.image.size }; 

change yPadding you need.
It can be negative when image's height is large than line height.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!