ios - NSTextAttachment 图片对齐

标签 ios image sdk uitextview nstextattachment

我正在学习这个很酷的教程 Implementing Rich Text with Images on OS X and iOS由@Duncan Groenewald 开发,能够在我的 UITextView 中显示图像。然而,这些图像并没有像我希望的那样居中。看图

NSTextAttachment sample image

如您所见,我希望图像以 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/

相关文章:

ios - 几个小时后推送通知的委托(delegate)方法未命中

ios - iOS 中场景和 View 的区别

jquery - 使用 jQuery 切换图像

sdk - 在 Rally 中查询用户故事修订

ios - 如何限制 UIPinchGestureRecognizer 中捏合缩放的最大/最小比例

ios - 在部分之间移动单元格时 UITableView 返回错误的索引路径

CSS 'background-attribute: fixed' 但对于图像

c# - 通过矩形显示图像差异

java - 如何从 APi.ai 的 Java SDK 获取 Json

sdk - [WARN] 当前工作目录 (C :\xampp\htdocs\sencha folder) is not a recognized Sencha SDK or application folder.