如何使用iOS7 Text Kit在附件周围包装文本?

18

我正在使用新的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];

这个工作正常,我可以看到我的图像呈现在输出中。然而,我找不到任何方法来指定图像对齐方式,或让文本环绕图像。

有什么想法吗?

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

3个回答

20

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(换行符)将其包围起来。只需将其附加到附件的属性字符串的两侧即可。 希望对您有所帮助,我花了很长时间才弄清楚。

这非常有帮助。谢谢分享! - CodeBrew

10

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

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

因此应该是:

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

1
哦,太好了!这终于让我能够垂直定位我的图片了。 - DarkDust
它有效!这应该被接受为最佳答案。简单而直接。 - Songlin

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

您需要更改yPadding。
当图像高度大于行高时,它可以为负数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接