根据window高度扩展NSViewRepresentable(NSTextView)高度

Expand NSViewRepresentable (NSTextView) height based on window height

我创建了一个 NSViewRepresentable 结构来管理 NSTextView 的状态。默认情况下,该视图只有一行,我想将其扩展到 window.

的边缘

视图定义如下:

struct Editor: View, NSViewRepresentable {

    @Binding var text: String

    func makeNSView(context: Context) -> NSTextView {
        let view = NSTextView()
        view.font = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular)
        return view
    }

    func updateNSView(_ view: NSTextView, context: Context) {
        let attributedText = NSMutableAttributedString(string: text)
        view.textStorage?.setAttributedString(attributedText)
    }
}

它目前看起来是这样的,它会随着你的进行添加行。 有没有办法让深色文本区域自动扩展到 window 的底部?

您可以使用 NSTextView.scrollableTextView() 来执行此操作:

struct ContentView : View {
    @State var text = ""
    var body: some View {
        VStack {
            Editor(text: $text)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}

struct Editor: View, NSViewRepresentable {

    @Binding var text: String

    func makeNSView(context: Context) -> NSView {
        let scrollView = NSTextView.scrollableTextView()
        guard let textView = scrollView.documentView as? NSTextView else {
            return scrollView
        }
        textView.font = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular)
        context.coordinator.textView = textView
        return scrollView
    }

    func updateNSView(_ view: NSView, context: Context) {
        let attributedText = NSMutableAttributedString(string: text)
        context.coordinator.textView?.textStorage?.setAttributedString(attributedText)
    }
    
    func makeCoordinator() -> Coordinator {
        return Coordinator()
    }
    
    class Coordinator {
        var textView : NSTextView?
    }
}