我希望在macOS的Swift UI中创建一个可编辑的多行文本框。我想创建一个语法突出显示文本编辑器,所以它将是多行的,并在各行中改变样式。在框架的当前状态下,这是可能的吗?我在网上几乎找不到任何关于它的文档。
发布于 2019-12-26 23:57:51
这可能会很有用,这是我用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,并调整代码以适应这种更简单的情况。
发布于 2019-10-06 00:06:16
您可以在SwiftUI中使用多行TextField
(只需在其上调用.lineLimit(N)
即可使用多行),但目前不支持具有多个独立样式的文本。TextField
只有一种字体和样式。
不过,您也可以自己动手:创建一个提供NSTextView
的NSViewRepresentable
实现,并将其绑定到一个NSMutableAttributedText
属性。您将需要自己处理所有的文本视图模型同步和绑定更新,但这肯定是可行的。
https://stackoverflow.com/questions/58251487
复制