gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:12:42 26 4
gpt4 key购买 nike

我想在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com