swift - 如何从 TextView 中复制不同字体的文本,并在粘贴到消息等其他应用程序时使用相同的字体?

标签 swift uipasteboard

这一行只复制没有字体的文本本身并粘贴它有效:

pasteBoard.string = MainController.customTextView.text 

我已经尝试查看人们就此问题提出的类似答案,但我看到的几乎每个答案都在 Objective C 中且已过时。通过查看其他答案,例如 this我想我的副本工作正常,但是当我粘贴复制的文本时,它没有粘贴任何内容。这是我的复制功能:

    @objc func handleCopyButton() {
    MainController.customTextView.resignFirstResponder() // dismiss keyboard

    // Setup code in overridden UITextView.copy/paste
    let selectedRange = MainController.customTextView.selectedRange
    let selectedText = MainController.customTextView.attributedText.attributedSubstring(from: selectedRange)

    // UTI List
    let utf8StringType = "public.utf8-plain-text"
    let rtfdStringType = "com.apple.flat-rtfd"

    // Try custom copy
    do {
        // Convert attributedString to rtfd data
        let fullRange = NSRange(location: 0, length: selectedText.string.count)
        let data:NSData? = try selectedText.data(from: fullRange, documentAttributes: [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.rtfd]) as NSData

        if let data = data {

            // Set pasteboard values (rtfd and plain text fallback)
            pasteBoard.items = [[rtfdStringType: data], [utf8StringType: selectedText.string]]

        }
    } catch { print("Couldn't copy") }

    // Copy if custom copy not available
    MainController.customTextView.copy()
}

如果您对此有任何疑问,请告诉我。提前致谢!

编辑:对于我尝试做的事情,事实证明你不能复制和粘贴字体(至少在 iOS 上是这样,但在 MacOS 上我相信你可以),但你可以做的是复制和粘贴 unicode 字符看起来像不同的字体。检查this如果您感兴趣,请解决。

最佳答案

  • 这对消息不起作用,因为 Apple 只为消息使用系统字体。
  • 为了使其在其他应用程序上运行,他们必须支持它并为他们提供字体,如果在 iOS 上,应用程序本身必须安装字体。
  • 如果你想让你的文本出现,那么你可以使用 UIPasteboard.general.string = stringVar
  • 尝试 this 中的一些建议计算器问题。

关于swift - 如何从 TextView 中复制不同字体的文本,并在粘贴到消息等其他应用程序时使用相同的字体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57168482/

相关文章:

ios - 将屏幕外的 SwiftUI View 居中

ios - 尝试在时间间隔后清除粘贴板

ios - 将 GIF 复制到 UIPasteboard

ios - 如何控制 UIPastboard 中的 UIImage 大小?

nsarray - 在UIPasteboard中存储NSArray

ios - -retainCount 究竟有多不可靠?

ios - 在嵌套 block 中使用常量值时,Swift 1.2 会被破坏

ios - 如何通过 iMessage ios 8 发送音频文件

ios - UIPickerView 的 "reusing view"始终为 nil

ios - UICollectionView 消失