Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTextAttachment image alignment

I am following this cool tutorial Implementing Rich Text with Images on OS X and iOS by @Duncan Groenewald and was able to display images in my UITextView. However, these images are not centered they way I would like them to be. See image

NSTextAttachment sample image

As you can see, I would like my image to be centered on the X-axis.

I tried returning the rect with appropriate values in -attachmentBoundsForTextContainer:proposedLineFragment:glyphPosition:characterIndex but that did not help.

I also tried setting the NSKernAttributeName for the NSTextAttachment attributed string. But all it did was hide the image some how.

like image 809
unspokenblabber Avatar asked Nov 20 '14 18:11

unspokenblabber


1 Answers

Try setting the paragraph style on your attachment with a center alignment.

If your images are embedded in an attributed string as attachments, you can access them by enumerating through the attributed string's attachment attributes. For example:

    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)
        }
    }
like image 171
Alex Choi Avatar answered Oct 13 '22 00:10

Alex Choi