You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

macOS平台SwiftUI的TextEditor为何无法启用搜索功能?

解决macOS SwiftUI中TextEditor不响应cmd-F查找的问题

问题出在默认的SwiftUI TextEditor在macOS上不会自动绑定系统的查找替换命令——即便组件本身支持该功能,也需要手动配置来触发系统查找面板。

以下是两种可行的解决方法:

方法一:手动绑定系统查找命令

通过添加CommandGroup覆盖默认的查找命令,调用AppKit原生方法触发查找面板,同时确保TextEditor处于聚焦状态:

struct ContentView: View {
    @State var text = "blah blach blach"
    @FocusState private var isTextEditorFocused: Bool

    var body: some View {
        NavigationStack {
            TextEditor(text: $text)
                .focused($isTextEditorFocused)
                .navigationTitle("Edit Bio")
                .onAppear {
                    // 视图加载时自动聚焦TextEditor
                    isTextEditorFocused = true
                }
        }
        .commandGroup(replacing: .find) {
            Button("Find") {
                // 调用AppKit原生方法弹出查找面板
                NSApp.sendAction(#selector(NSTextView.showFindPanel(_:)), to: nil, from: nil)
            }
            .keyboardShortcut("f", modifiers: .command)
        }
    }
}

方法二:使用AppKit包装自定义TextEditor

如果需要更精细的控制,可以通过NSViewRepresentable包装NSTextView并启用内置的NSTextFinder:

struct CustomTextEditor: NSViewRepresentable {
    @Binding var text: String

    func makeNSView(context: Context) -> NSTextView {
        let textView = NSTextView()
        textView.isRichText = false
        // 启用文本查找功能
        let textFinder = NSTextFinder()
        textFinder.client = textView
        textView.findBarContainer?.addSubview(textFinder.findBarView)
        textFinder.showFindBar(true)
        return textView
    }

    func updateNSView(_ nsView: NSTextView, context: Context) {
        if nsView.string != text {
            nsView.string = text
        }
    }
}

// 使用自定义TextEditor
struct ContentView: View {
    @State var text = "blah blach blach"

    var body: some View {
        NavigationStack {
            CustomTextEditor(text: $text)
                .navigationTitle("Edit Bio")
        }
    }
}

关键说明:

  • 方法一的核心是确保TextEditor处于聚焦状态,并通过NSApp.sendAction触发原生查找面板,这是最简单的适配方式。
  • 方法二适合需要自定义查找行为的场景,直接使用AppKit的NSTextFinder实现完整的查找替换功能。

内容的提问来源于stack exchange,提问作者David Homes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 19:02:49