你可以使用 NSAttributedString 来为 NSTextView 设置属性字符串。下面是一个示例代码:
import Cocoa
// 创建一个 NSAttributedString
let attributedString = NSAttributedString(string: "Hello, World!", attributes: [
.font: NSFont.systemFont(ofSize: 18),
.foregroundColor: NSColor.red,
.backgroundColor: NSColor.yellow
])
// 创建一个 NSTextView
let textView = NSTextView(frame: NSRect(x: 0, y: 0, width: 200, height: 200))
// 将属性字符串绑定到 NSTextView
textView.textStorage?.setAttributedString(attributedString)
// 在窗口中显示 NSTextView
let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 400, height: 400),
styleMask: [.titled, .closable, .miniaturizable, .resizable],
backing: .buffered,
defer: false)
window.contentView?.addSubview(textView)
window.makeKeyAndOrderFront(nil)
// 运行应用程序的主事件循环
NSApp.run()
这段代码创建了一个属性字符串 NSAttributedString,并将其绑定到 NSTextView 的 textStorage 属性上,然后将 NSTextView 显示在窗口中。你可以根据需要自定义属性字符串的样式和 NSTextView 的外观。