SwiftUI中的多行可编辑文本字段 [英] Multiline editable text field in SwiftUI

查看:113
本文介绍了SwiftUI中的多行可编辑文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking to create an editable multi-line text box in Swift UI for macOS. I'd like to create a syntax highlighting text editor, so it'd be multi-line and change styles throughout the lines. Is this possible with the framework in its current state? I can find barely any documentation about it online.

推荐答案

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

it can be useful, this is my first solution to get an NSTextView with SwiftUI:

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
  }

}

如果像我一样,您只需要编辑一些没有属性的文本,则可以仅用String替换NSAttributedString,并针对这种较简单的情况修改代码.

If like me, you just need to edit some text without attributes, you can replace NSAttributedString with just String and adapt the code for this simpler case.

这篇关于SwiftUI中的多行可编辑文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆