3

我希望在 macOS 的 Swift UI 中创建一个可编辑的多行文本框。我想创建一个语法高亮文本编辑器,所以它会是多行的,并且可以在所有行中更改样式。这在当前状态下的框架是否可行?我在网上几乎找不到任何关于它的文档。

4

2 回答 2

1

它很有用,这是我第一个使用 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 并针对这种更简单的情况调整代码。

于 2019-12-26T23:57:50.520 回答
-4

您可以在 SwiftUI 中使用多行TextField(您只需要调用.lineLimit(N)它即可成为多行功能),但目前不支持具有多种单独样式的文本。ATextField只有一个字体和样式。

不过,您可以自己滚动它:创建一个NSViewRepresentable实现,NSTextView将其绑定到一个NSMutableAttributedText属性。您需要自己处理所有文本视图模型同步和绑定更新,但这当然是可行的。

于 2019-10-06T00:06:16.420 回答