【问题标题】:NSTextAttachment image not shown in NSTextView (but in UITextView)?NSTextAttachment 图像未显示在 NSTextView 中(但在 UITextView 中)?
【发布时间】:2016-03-19 18:56:21
【问题描述】:

我在获取 NSTextAttachment 图像以在 OS X 应用程序的 NSTextView 中工作时遇到问题。

NSTextAttachment 的图像根本不显示。但是,它似乎仍然设置正确。因为当复制NSTextView 的内容并将其粘贴回例如TextEdit.app,粘贴的文本包含正确的图像。

这是重现问题的最小游乐场:

import Cocoa

let img = NSImage(named: "Checked")

let textView = NSTextView(frame: NSMakeRect(0, 0, 254, 64))

let attrstr = NSMutableAttributedString(string: "Test")

let attch = NSTextAttachment()
attch.image = img

attrstr.appendAttributedString(NSAttributedString(attachment: attch))

textView.textStorage!.setAttributedString(attrstr)

textView

预期输出:

对于 iOS,因此使用 UIKit 代替 Cocoa,它工作得非常好:

import UIKit

let img = UIImage(named: "Checked")

let textView = UITextView(frame: CGRectMake(0.0, 0.0, 200.0, 44.0))

let attrstr = NSMutableAttributedString(string: "Test")

let attch = NSTextAttachment()
attch.image = img

attrstr.appendAttributedString(NSAttributedString(attachment: attch))

textView.attributedText = attrstr

textView

我使用的是 XCode 7。两个 Playground 都可以下载here

非常欢迎任何想法,提前致谢!

【问题讨论】:

    标签: ios xcode swift macos


    【解决方案1】:
    var thumbnailImage: NSImage? = // some image
    var attachmentCell: NSTextAttachmentCell = NSTextAttachmentCell.initImageCell(thumbnailImage!)
    var attachment: NSTextAttachment = NSTextAttachment()
    attachment.attachmentCell = attachmentCell
    var attrString: NSAttributedString = NSAttributedString.attributedStringWithAttachment(attachment)
    self.textView.textStorage().appendAttributedString(attrString)
    

    【讨论】:

    • 谢谢,工作得很好!我真的很感激!
    • 谢谢!您知道如何提供带有单元格图像的拖放功能吗?默认情况下,如果我将它拖到 Finder,它会创建一个空文本文件
    猜你喜欢
    • 1970-01-01
    • 2018-10-19
    • 2023-03-25
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    相关资源
    最近更新 更多