我正在使用新的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];
这工作得很好,我可以在输出中看到渲染的图像。但是,我找不到任何方法来指定图像对齐方式,或者在图像周围换行。
有什么想法吗?
注意:文本附件不同于排除路径-文本附件是“模型”的一部分,即它是布局管理器对其执行文本布局的属性文本字符串的一部分。而排除路径是视图的一部分。
发布于 2013-11-05 20:08:31
NSAttributedString
将NSTextAttachments
视为单个字符。因此,为了调整它们的对齐方式,您必须像处理文本一样进行调整。我花了几个小时摆弄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
(换行符)把它括起来。只需将这些附加到附件的属性字符串的两边。
希望这能帮上忙,我花了很长时间才弄明白。
发布于 2013-09-26 16:00:58
尝试将bounds
属性设置为图像大小。
定义了接收方的图形表示在文本坐标系中的布局边界。
所以它应该是:
ta.bounds = (CGRect) { 0, 0, ta.image.size };
发布于 2014-12-01 14:06:32
ta.bounds = (CGRect) { 0, yPadding, ta.image.size };
根据需要更改yPadding。
当图像的高度大于行的高度时,它可以是负数。
https://stackoverflow.com/questions/18968820
复制相似问题