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

SwiftUI macOS Big Sur环境下应用启动时如何自动聚焦TextEditor

解决方案

兼容 macOS Big Sur (11.x)方案

Big Sur 版本下 SwiftUI 未提供原生聚焦控制API,需通过桥接 AppKit 实现自动聚焦,无需复杂自定义代码,可按以下步骤实现:

  1. 实现可自动聚焦的TextEditor包装组件:
struct FocusableTextEditor: NSViewRepresentable {
    @Binding var text: String
    var isFirstResponder: Bool = false

    func makeNSView(context: Context) -> NSTextView {
        let textView = NSTextView()
        textView.string = text
        return textView
    }

    func updateNSView(_ nsView: NSTextView, context: Context) {
        nsView.string = text
        if isFirstResponder, nsView.window != nil, !nsView.isFirstResponder {
            DispatchQueue.main.async {
                nsView.window?.makeFirstResponder(nsView)
            }
        }
    }
}
  1. 在你的MailView中替换原生TextEditor,并在视图出现时触发聚焦:
struct MailView: View {
    let mail: Mail
    @State private var fullText: String = "This is some editable text..."
    @State private var editorShouldFocus = false

    var body: some View {
        VStack(alignment: .leading) {
            FocusableTextEditor(text: $fullText, isFirstResponder: editorShouldFocus)
        }
        .onAppear {
            editorShouldFocus = true
        }
    }
}
  1. 应用启动时默认选中第一个条目后,右侧MailView加载时会自动触发onAppear,完成TextEditor的自动聚焦。

若首次启动偶现聚焦失败,可将makeFirstResponder的调用逻辑增加0.1秒延迟,抵消三栏布局的视图渲染耗时:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    nsView.window?.makeFirstResponder(nsView)
}

macOS Monterey 及以上(12.0+)原生方案

更高版本系统可直接使用FocusState原生API实现,代码更简洁:

struct MailView: View {
    let mail: Mail
    @State private var fullText: String = "This is some editable text..."
    @FocusState private var isEditorFocused: Bool

    var body: some View {
        VStack(alignment: .leading) {
            TextEditor(text: $fullText)
                .focused($isEditorFocused)
        }
        .onAppear {
            isEditorFocused = true
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 16:24:05