SwiftUI 中的多行可编辑文本字段

2024-02-21

我正在寻找在 macOS 的 Swift UI 中创建一个可编辑的多行文本框。我想创建一个语法突出显示文本编辑器,因此它是多行的,并可以更改各行的样式。在当前状态下,这可能吗?我在网上几乎找不到任何有关它的文档。


它可能很有用,这是我使用 SwiftUI 获取 NSTextView 的第一个解决方案:

import SwiftUI
import os

let uiLog = OSLog(subsystem: "com.visual-science.CryptiK", category: "UI")

class  EditorCoordinator : NSObject, NSTextViewDelegate {
  let textView: NSTextView;
  let scrollView : NSScrollView
  let text : Binding<NSAttributedString>

  init(binding: Binding<NSAttributedString>) {
    text = binding

    textView = NSTextView(frame: .zero)
    textView.autoresizingMask = [.height, .width]
    textView.textStorage?.setAttributedString(text.wrappedValue)
    textView.textColor = NSColor.textColor

    scrollView = NSScrollView(frame: .zero)
    scrollView.hasVerticalScroller = true
    scrollView.autohidesScrollers = false
    scrollView.autoresizingMask = [.height, .width]
    scrollView.documentView = textView

    super.init()
    textView.delegate = self
  }

  func textDidChange(_ notification: Notification) {
    switch  notification.name {
    case NSText.didChangeNotification :
      text.wrappedValue = (notification.object as? NSTextView)?.textStorage ?? NSAttributedString(string: "")
    default:
      os_log(.error, log: uiLog, "Coordinator received unwanted notification")
    }
  }

}

struct DataTextEditorView: View, NSViewRepresentable {
  typealias Coordinator = EditorCoordinator
  typealias NSViewType = NSScrollView

  let text : Binding<NSAttributedString>

  func makeNSView(context: NSViewRepresentableContext<DataTextEditorView>) -> DataTextEditorView.NSViewType {
    os_log(.info, log: uiLog, "%@", context.coordinator.scrollView)
    return context.coordinator.scrollView
  }

  func updateNSView(_ nsView: NSScrollView, context: NSViewRepresentableContext<DataTextEditorView>) {
    os_log(.debug, log: uiLog, "%@", context.coordinator.self)
    os_log(.debug, log: uiLog, "%@", text.wrappedValue)
  }

  func makeCoordinator() -> EditorCoordinator {
    os_log(.info, log: uiLog, "makeCoordinator")
    let coordinator =  EditorCoordinator(binding: text)
    return coordinator
  }

}

如果像我一样,您只需要编辑一些没有属性的文本,您可以将 NSAttributedString 替换为 String 并针对这种更简单的情况调整代码。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SwiftUI 中的多行可编辑文本字段 的相关文章

随机推荐