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

SwiftUI中NavigationView内的EditButton无法激活编辑模式

SwiftUI列表无法编辑、EditButton不显示的修复方案

问题原因及修复步骤:

  1. 废弃API导致按钮不显示
    Xcode14对应iOS16及以上版本中,navigationBarItems已被官方废弃,需使用toolbarAPI来添加导航栏按钮。

  2. 修饰符位置错误
    navigationTitle和导航栏按钮的修饰符必须添加到NavigationView内部的子视图上(比如示例中的List),而不是直接作用于NavigationView本身,否则导航栏元素会失效。

修正后的完整代码:

import SwiftUI

struct ListTutorialBootcamp: View {
    @State private var fruits: [String] = ["Apple", "banana", "grape", "Orange", "Peach"]
    
    func delete(indexSet: IndexSet) {
        fruits.remove(atOffsets: indexSet)
    }
    
    var body: some View {
        NavigationView {
            List {
                ForEach(fruits, id: \.self) { fruit in
                    Text(fruit.capitalized)
                }
                .onDelete(perform: delete)
            }
            .navigationTitle("Grocery List")
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    EditButton()
                }
            }
        }
    }
}

struct ListTutorialBootcamp_Previews: PreviewProvider {
    static var previews: some View {
        ListTutorialBootcamp()
    }
}

修改完成后,EditButton会正常显示在导航栏左侧,点击即可进入列表编辑模式,支持左滑删除或选中批量删除操作。如果需要添加排序功能,可额外给ForEach添加.onMove(perform:)方法,并在toolbar中添加对应按钮。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 02:41:04