【问题标题】:How to wrap text around attachments using iOS7 Text Kit?如何使用 iOS7 Text Kit 在附件周围环绕文本?
【发布时间】:2013-09-23 21:02:15
【问题描述】:

我正在使用新的 Text Kit API 为某些属性文本添加附件:

// create an attachment for each image
NSTextAttachment* ta = [NSTextAttachment new];
ta.image = [UIImage imageNamed:@"imageName"];

// add to the attributed text string
NSAttributedString* rep = [NSAttributedString attributedStringWithAttachment:ta];
[myAttributedTextString appendAttributedString:rep];

这很好用,我可以在输出中看到我的图像。但是,我找不到任何方法来指定图像对齐或在图像周围环绕文本。

有什么想法吗?

注意:文本附件与排除路径不同 - 文本附件是“模型”的一部分,即它是布局管理器执行文本布局的属性文本字符串的一部分。而排除路径是视图的一部分。

【问题讨论】:

    标签: ios objective-c uikit ios7 textkit


    【解决方案1】:

    NSTextAttachmentsNSAttributedString 视为单个字符。因此,为了调整它们的对齐方式,您必须像处理文本一样这样做。我花了几个小时摆弄attachment.bounds(我永远无法正常工作)才最终弄清楚这一点。下面是一个如何水平对齐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])];
    

    在此之后,您可以将imageAttrString 附加到现有的属性字符串,并可能在其后附加另一个。一个怪癖是,因为附件是一个字符,所以它不被视为自己的段落。为此,您需要用\n(换行符)将其包围。只需将这些附加到附件属性字符串的两侧即可。

    希望有帮助,我花了很长时间才弄明白。

    【讨论】:

    • 这很有帮助。感谢分享!
    【解决方案2】:

    尝试将bounds 属性设置为图像大小。

    定义文本坐标系中接收器图形表示的布局边界。

    应该是这样的:

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

    【讨论】:

    • 噢噢,太好了!这终于让我可以垂直定位我的图像了。
    • 有效!这应该是公认的最佳答案。简单直接
    【解决方案3】:
    ta.bounds = (CGRect) { 0, yPadding, ta.image.size }; 
    

    更改您需要的 yPadding。
    图片的高度大于行高时可以为负数。

    【讨论】:

      猜你喜欢
      • 2010-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多