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

SwiftUI中SplitView仅首个列表项可响应,后续项点击无作用

SwiftUI列表仅首个条目可跳转的问题解决

问题根源

你的selectedEntryID声明为ObjectId?类型,但JournalEntry的主键id是String类型(由UUID().uuidString生成),类型不匹配导致列表的selection绑定无法正确更新选中状态。点击第一个条目偶然触发跳转后,后续条目点击无法更新选中ID,因此始终停留在首个选中状态且无响应。

修复方案

将selectedEntryID的类型修改为String?,与JournalEntry.id的类型保持一致:

struct JournalListView: View {
    @ObservedResults(JournalEntry.self) var journalEntries
    
    // 修正类型为String?,匹配JournalEntry的id类型
    @State private var selectedEntryID: String?
    @State private var showingAddNewJournalEntry = false
    
    var body: some View {
        List(journalEntries, id: \.id, selection: $selectedEntryID) { entry in
            NavigationLink(destination: JournalEntryView(entryToEdit: entry)) {
                VStack(alignment: .leading) {
                    Text(entry.name)
                        .font(.system(size: 25))
                        .multilineTextAlignment(.leading)
                    Text(entry.date.description)
                        .font(.system(size: 10))
                        .multilineTextAlignment(.leading)
                    Text(entry.body)
                        .truncationMode(.tail)
                        .lineLimit(3)
                }
            }
            .cornerRadius(15)
            .padding(.horizontal, 15)
        }
        .listRowInsets(EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10))
        .toolbar {
            ToolbarItem(placement: .automatic) {
                Button {
                    showingAddNewJournalEntry = true
                } label: {
                    Image(systemName: "plus")
                }
            }
        }
        .sheet(isPresented: $showingAddNewJournalEntry, content: {
            JournalEntryView()
        })
    }
}

额外说明

由于JournalEntry已经遵循ObjectKeyIdentifiable协议,列表中的id: \.id参数可以省略,但这不是导致问题的原因,核心修复点仍为选中ID的类型匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 21:53:13