gpt4 book ai didi

ios - 使用 AttributedString 立即格式化 UITextView

转载 作者:行者123 更新时间:2023-12-03 08:32:21 24 4
gpt4 key购买 nike

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

为了格式化行,我使用 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 的默认样式。

我想要什么:

用户正在输入特定格式的行,然后他按回车。下一行格式化为另一种即时预定义样式。

示例:

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

重要说明:

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

最佳答案

好吧,我刚刚弄清楚如何使用 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

非常简单!

关于ios - 使用 AttributedString 立即格式化 UITextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64748034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com