【问题标题】:Instantly format a UITextView using AttributedString使用 AttributedString 立即格式化 UITextView
【发布时间】:2021-02-21 03:49:41
【问题描述】:

我正在开发一个 macOS 富文本编辑器,它为文本视图的每一行应用预定义的样式。

为了格式化这些行,我使用了NSAttributedString,然后,我将该字符串插入到我的UITextView 中。为了让事情变得更简单,我使用了一个名为 SwiftRichString 的工具。

我的代码如下所示。它直截了当,效果很好。

import Cocoa
import SwiftRichString
import AppKit

class ViewController: NSViewController {
    @IBOutlet var textView: NSTextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Format the string
        let style = Style {
            $0.font = NSFont(name: "Arial", size: 20)
            $0.color = NSColor.black
            $0.alignment = .center
        }
        let attributedText = "Hello World!".set(style: style)

        // Add formatted string to the text view
        textView.textStorage?.append(attributedText)
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

}

现状:

用户正在输入格式化的行。然后当用户点击 Return 并输入内容时,新行的格式会返回 UITextView 的默认样式。

我想要什么:

用户正在输入特定格式的行,然后他点击 Return。下一行应该被格式化为另一种预定义的样式on-the-go

示例:

  1. 用户正在输入 标题 行。当前样式为(Arial,粗体,20pt)。
  2. 他点击返回
  3. 下一行的样式应为 Normal 使用预定义样式(Arial,12pt)的文本。

重要提示:

在我上面的代码中,我能够轻松地格式化该行,因为它是硬编码的。我真正的问题是,如何立即格式化下一行,因为下一行将由用户输入。样式应在用户开始编写之前应用到下一行。

【问题讨论】:

标签: ios swift macos textview uitextview


【解决方案1】:

好的,我刚刚想出了如何使用typingAttributtes 来解决这个问题(感谢@Larme 的提示)。

   // Define next attributes
   let attributes: [NSAttributedString.Key: Any] = [
       .foregroundColor: NSColor.red,
       .font: NSFont(name: "Arial", size: 12)!,
   ]
   
   // Assign attributes to the text view typing attributes
   textView.typingAttributes = attributes

非常简单!

【讨论】:

    【解决方案2】:

    请原谅题外话。如果您正在制作文本编辑器,您可以考虑使用表格视图,其中每个文本行都是一个单元格 - 作为程序员,这对您来说是额外的工作,但它会显着提高性能。这就是 Xcode 编辑器的构建方式。

    【讨论】:

      【解决方案3】:

      也许你可以使用optional func textViewDidChange(_ textView: UITextView)

      https://developer.apple.com/documentation/uikit/uitextviewdelegate/1618599-textviewdidchange

      更改后,只需解析文本,查找新行,拆分它们并应用您想要的所有样式

      【讨论】:

      • textViewDidChange(和 macOS 的 textDidChange)在这里不会做太多,因为我需要应用新样式 before 用户开始输入下一行。
      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 2014-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多