SwiftUI macOS Big Sur环境下应用启动时如何自动聚焦TextEditor
解决方案
兼容 macOS Big Sur (11.x)方案
Big Sur 版本下 SwiftUI 未提供原生聚焦控制API,需通过桥接 AppKit 实现自动聚焦,无需复杂自定义代码,可按以下步骤实现:
- 实现可自动聚焦的
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) } } } }
- 在你的
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 } } }
- 应用启动时默认选中第一个条目后,右侧
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
相关产品推荐
相关产品推荐

