How to wrap text around attachments using iOS7 Text Kit? How to wrap text around attachments using iOS7 Text Kit? ios ios

How to wrap text around attachments using iOS7 Text Kit?


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 imageNSTextAttachment *attachment = [[NSTextAttachment alloc] init];attachment.image = [UIImage imageNamed:@"sample_image.jpg"];NSMutableAttributedString *imageAttrString = [[NSAttributedString attributedStringWithAttachment:attachment] mutableCopy];// sets the paragraph styling of the text attachmentNSMutableParagraphStyle *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.