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

SwiftUI中EditButton修改列表后无法显示删除红圈问题

解决EditButton添加条目后无法显示删除按钮的问题

你的问题是:原本正常运行的EditButton(),在进入AddView()页面添加条目返回MainView后,无法显示用于删除条目的红色圆圈,即使手动修改列表条目也无法恢复功能。

问题原因

你的Person结构体没有遵循Identifiable协议,ForEach需要依靠唯一标识来跟踪列表中每个视图的状态。新增条目后,SwiftUI无法识别这些新元素的唯一身份,导致编辑模式下的删除按钮无法正常渲染。

解决方案

让Person结构体遵循Identifiable协议,为每个实例生成唯一的id:

import SwiftUI

// 新增Identifiable协议遵循,并添加自动生成的唯一ID
struct Person: Identifiable {
    let id = UUID()
    var name: String
    var age: Int
}

struct ContentView: View {
    
    @State var array: [Person] = [Person(name: "Tim", age: 23), Person(name: "Marie", age: 24)]

    
    var body: some View {
        NavigationView{
            List{
                ForEach(array) {item in
                    Text(item.name)
                }
                .onDelete { indexSet in
                    array.remove(atOffsets: indexSet)
                }
            }
            .toolbar {
                EditButton()
                NavigationLink("AddView", destination: AddView(array: $array))
            }
        }
    }
}

struct AddView: View{
    
    @State var text: String = ""
    @Binding var array: [Person]
    
    var body: some View{
        VStack {
            TextField("Type here", text: $text)
            Button("Add") {
                array.append(Person(name: text, age: 14))
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

说明

修改后,每个Person实例都会自动拥有一个唯一的UUID作为标识,SwiftUI可以准确跟踪每个列表项的状态。返回主视图后点击EditButton,就能正常显示删除用的红色圆圈,编辑功能也能恢复正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 05:07:24