NSTextAttachments
被视为单个字符NSAttributedString
。因此,为了调整它们的对齐方式,您必须像处理文本一样这样做。我花了几个小时摆弄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
(换行符)包围它。只需将这些附加到附件属性字符串的两侧即可。
希望有帮助,我花了很长时间才弄清楚。