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

标签 swift macos swiftui macos-catalina

我想在 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 并针对这种更简单的情况调整代码。

关于swift - SwiftUI 中的多行可编辑文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58251487/

相关文章:

ios - osx 上的 sem_open 共享内存在哪里

python - OSX 使用 os.system 运行 Scrapy 脚本

linux - 通过 ssh (linux/osx) 运行作业

SwiftUI 和 CloudKit 异步数据加载

ios - 我一整天都在尝试计算用户字符并将它们打印到屏幕上

ios - 删除动态调整 TableView 的行?

php - Braintree 事务中未定义后置变量

swift - AUHostMusicalContextBlock "An audio unit accessing this property should cache it in realtime-safe storage before beginning to render."

swiftui - 如何访问 SwiftUI 中的 subview ?

ios - 快速传递带参数的闭包作为参数