From 9fbfe22fa6635d16a48441e19dca858d37b8615d Mon Sep 17 00:00:00 2001 From: ShikiSuen Date: Tue, 21 Feb 2023 22:58:08 +0800 Subject: [PATCH] SwiftUIExtension // Porting read-only NSTextField to SwiftUI. --- .../SwiftExtension/SwiftUIExtension.swift | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Packages/vChewing_SwiftExtension/Sources/SwiftExtension/SwiftUIExtension.swift b/Packages/vChewing_SwiftExtension/Sources/SwiftExtension/SwiftUIExtension.swift index 870cbee7..680da105 100644 --- a/Packages/vChewing_SwiftExtension/Sources/SwiftExtension/SwiftUIExtension.swift +++ b/Packages/vChewing_SwiftExtension/Sources/SwiftExtension/SwiftUIExtension.swift @@ -172,3 +172,26 @@ public extension AppProperty { ) } } + +// MARK: - Porting NSTextField (Label) to SwiftUI. + +@available(macOS 10.15, *) +public struct AttributedLabel: NSViewRepresentable { + private let text: NSAttributedString + + public init(attributedString: NSAttributedString) { + text = attributedString + } + + public func makeNSView(context _: Context) -> NSTextField { + let textField = NSTextField(labelWithAttributedString: text) + textField.isSelectable = false + textField.allowsEditingTextAttributes = false + textField.preferredMaxLayoutWidth = textField.frame.width + return textField + } + + public func updateNSView(_ nsView: NSTextField, context _: Context) { + nsView.attributedStringValue = text + } +}