NSTextAttachment图像对齐

uns*_*ber 8 sdk image uitextview nstextattachment ios

我正在关注这个很酷的教程@Duncan Groenewald 在OS X和iOS上使用图像实现富文本,并能够在我的显示中显示图像UITextView.但是,这些图像并没有按照我希望的方式居中.见图

NSTextAttachment样本图像

如您所见,我希望我的图像以X轴为中心.

我尝试rect使用适当的值返回,-attachmentBoundsForTextContainer:proposedLineFragment:glyphPosition:characterIndex但没有帮助.

我也尝试设置NSKernAttributeNameNSTextAttachment属性串.但它所做的只是隐藏图像.

小智 6

尝试使用中心对齐方式在附件上设置段落样式.

如果您的图像作为附件嵌入到属性字符串中,则可以通过枚举属性字符串的附件属性来访问它们.例如:

    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)
        }
    }
Run Code Online (Sandbox Code Playgroud)


Luc*_*nzo 5

这是使用扩展名的Swift 3.1

extension NSMutableAttributedString {

    func setAttachmentsAlignment(_ alignment: NSTextAlignment) {
        self.enumerateAttribute(NSAttachmentAttributeName, in: NSRange(location: 0, length: self.length), options: .longestEffectiveRangeNotRequired) { (attribute, range, stop) -> Void in
            if attribute is NSTextAttachment {
                let paragraphStyle = NSMutableParagraphStyle()
                paragraphStyle.alignment = alignment
                self.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: range)
            }
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以轻松地对属性字符串上的附件应用对齐方式:

let attributeString = NSMutableAttributedString(string: "")
// add attachments
attributeString.setAttachmentsAlignment(.center) 
Run Code Online (Sandbox Code Playgroud)