我正在学习这个很酷的教程 Implementing Rich Text with Images on OS X and iOS由@Duncan Groenewald 开发,能够在我的 UITextView
中显示图像。然而,这些图像并没有像我希望的那样居中。看图
如您所见,我希望图像以 X 轴为中心。
我尝试在 -attachmentBoundsForTextContainer:proposedLineFragment:glyphPosition:characterIndex
中返回具有适当值的 rect
但这没有帮助。
我还尝试为 NSTextAttachment
属性字符串设置 NSKernAttributeName
。但它所做的只是以某种方式隐藏图像。
最佳答案
尝试将附件的段落样式设置为居中对齐。
如果您的图像作为附件嵌入到属性字符串中,您可以通过枚举属性字符串的附件属性来访问它们。 例如:
attributedContent.enumerateAttribute(NSAttachmentAttributeName, inRange: NSRange(location: 0, length: attributedContent.length), options: nil) { (attribute, range, stop) -> Void in
if let attachment = attribute as? NSTextAttachment {
// this example assumes you want to center all attachments. You can provide additional logic here. For example, check for attachment.image.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .Center
attributedContent.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: range)
}
}
关于ios - NSTextAttachment 图片对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27046797/