How to wrap text around attachments using iOS7 Text Kit?

后端 未结 3 1563
自闭症患者
自闭症患者 2021-01-31 20:09

I am using the new Text Kit API to add attachments to some attributed text:

// create an attachment for each image
NSTextAttachment* ta = [NSTextAttachment new];         


        
相关标签:
3条回答
  • 2021-01-31 20:33

    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 };
    
    0 讨论(0)
  • 2021-01-31 20:35

    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.

    0 讨论(0)
  • 2021-01-31 20:40
    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.

    0 讨论(0)
提交回复
热议问题