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

SwiftUI列表无数据时如何卸载NavigationLink目标视图并显示默认提示

问题根因

删除最后一条笔记后,selectedNoteId仍然存储着已删除笔记的ID值,NavigationView无法匹配到对应的NavigationLink标签,就不会自动切换到你定义的默认占位视图,因此会残留最后一次加载的NoteView内容。

解决方案

只需要在删除逻辑末尾增加判断,当笔记数组被清空时,手动将selectedNoteId置为nil即可触发导航回到默认占位状态,修改后的removeNote代码如下:

func removeNote() {
    if let selection = selectedNoteId,
       let selectionIndex = data.notes.firstIndex(where: { $0.id == selection }) {
        data.notes.remove(at: selectionIndex)
        // 新增清空选中ID的逻辑
        if data.notes.isEmpty {
            selectedNoteId = nil
        }
        // 若需要删除后自动选中下一条,可补充以下逻辑
        // else {
        //     let targetIndex = min(selectionIndex, data.notes.endIndex - 1)
        //     selectedNoteId = data.notes[targetIndex].id
        // }
    }
}

补充说明

NavigationLink的selection绑定值为nil时,多列导航的详情列会自动渲染你在NavigationView里定义的默认视图,也就是你写的Text("Select a note or create a new one..."),完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:12:03