如何在退出TextEditor时禁用.searchable的自动聚焦功能?
解决SwiftUI关闭Popover后光标自动跳转到搜索框的问题
这个问题是因为SwiftUI的.searchable组件默认会在主界面重新获得交互权时自动获取焦点。要禁用这个行为,我们可以通过手动控制搜索框的焦点状态来实现:
具体步骤:
- 添加
@FocusState变量管理搜索框的焦点状态 - 将搜索框的焦点状态与该变量绑定
- 监听Popover的显示状态,在Popover关闭时强制取消搜索框的焦点
修改后的完整代码:
import SwiftUI struct ContentView: View { @State private var searchText = "" @State private var showPopoverComment = false @State var comment: String = "" // 新增:控制搜索框焦点的状态变量 @FocusState private var isSearchFocused: Bool var body: some View { VStack { Button("打开评论弹窗", action: {showPopoverComment = true}) } .searchable(text: $searchText, placement: .toolbar, prompt: "搜索") // 绑定搜索框的焦点状态 .focused($isSearchFocused) .popover(isPresented: $showPopoverComment) { TextEditor(text: $comment) .frame(width: 100, height: 100) } // 监听Popover状态变化,关闭时取消搜索框焦点 .onChange(of: showPopoverComment) { oldValue, newValue in if oldValue && !newValue { isSearchFocused = false } } } }
原理说明:
@FocusState是SwiftUI专门用于管理视图焦点的属性包装器,通过它可以精准控制哪个视图获得焦点.onChange(of: showPopoverComment)监听弹窗的显示状态,当弹窗从显示变为隐藏时,立即将搜索框的焦点状态设为false,阻止系统自动给搜索框分配焦点
内容的提问来源于stack exchange,提问作者Sviatoslav
相关产品推荐
相关产品推荐

