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

macOS中SwiftUI .searchable(placement: .sidebar)输入光标跳转问题

macOS NavigationSplitView侧边栏搜索框光标跳转问题修复

问题现象

在macOS 13.4.1、Xcode 14.3.1环境下,给NavigationSplitView添加placement: .sidebar的搜索框时,输入内容时光标会异常跳转到文本末尾,无法在搜索查询开头正常添加字符。

复现代码

struct ContentView: View {
    @State var selection = ""
    @State var searchText = ""
    
    var body: some View {
        NavigationSplitView {
            List(selection: $selection) {
                Text("First")
                    .tag("first")
                
                Text("Second")
                    .tag("second")
                
                Text("Thrid")
                    .tag("third")
            }
        } detail: {
            VStack {
                Text("Detail page for: \(selection)")
                
                Text("Searching for: \(searchText)")
            }
        }
        .searchable(text: $searchText, placement: .sidebar)
    }
}

解决方案

将.searchable修饰符从全局的NavigationSplitView移至侧边栏的List组件上,缩小状态更新的作用域,避免因整个SplitView重绘导致光标位置异常。

修改后的代码:

struct ContentView: View {
    @State var selection = ""
    @State var searchText = ""
    
    var body: some View {
        NavigationSplitView {
            List(selection: $selection) {
                Text("First")
                    .tag("first")
                
                Text("Second")
                    .tag("second")
                
                Text("Third")
                    .tag("third")
            }
            .searchable(text: $searchText, placement: .sidebar)
        } detail: {
            VStack {
                Text("Detail page for: \(selection)")
                
                Text("Searching for: \(searchText)")
            }
        }
    }
}

原因说明

当.searchable应用到整个NavigationSplitView时,搜索文本的状态更新会触发整个SplitView的重绘,系统会重置搜索框的光标位置到文本末尾。将搜索框绑定到侧边栏的List后,状态更新仅影响侧边栏区域,不会干扰光标的正常定位逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 23:52:47