如何使用iOS7文本工具包围绕附件​​打包文本?

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

这工作正常,我可以看到我的图像呈现在输出。 但是,我无法find任何指定图像alignment的方法,或者在图像周围缠绕文本。

有任何想法吗?

注意:文本附件不同于排除path – 文本附件是“模型”的一部分,即它是布局pipe理器在其上执行文本布局的属性文本string的一部分。 而排除path是视图的一部分。

NSTextAttachmentsNSTextAttachments视为单个字符。 所以,为了调整自己的路线,你必须像对待文字一样进行。 我花了好几个小时来处理attachment.bounds (我永远无法正常工作),终于搞清楚了。 以下是如何水平alignmentNSTextAttachment

 #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追加到现有的属性string,也可以追加另一个string。 一个怪癖是,因为依恋是一个angular色,所以不被当作自己的段落。 为了做到这一点,你需要用\n (换行符)来包围它。 只需将这些附加到附件的归属string的两侧即可。

希望有所帮助,花了我很长时间才弄清楚。

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

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

所以它应该是:

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

改变你需要的yPadding。
当图像的高度大于线条高度时,可以是负值。