GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Why edit button is not working?

Forums > 100 Days of SwiftUI

import SwiftUI

struct ContentView: View { @State var courseCategoryList = ["SwiftUI", "Swift", "Machine Learning", "UIKit", "IOS", "ARKit"] @State private var selectedItem = Set<UUID>()

var body: some View {
    NavigationView {

        List(courseCategoryList, id: \.self, selection: $selectedItem) { category in
            Text(category)
                .font(.title3)
                .listRowBackground(RoundedRectangle(cornerRadius: 10).fill(Color.orange.opacity(0.2)))
        }

// .disabled(courseCategoryList.isEmpty) .navigationTitle("Dev Techie") .toolbar { EditButton() } } } func removeItem(at indexSet: IndexSet) { courseCategoryList.remove(atOffsets: indexSet) } }

1      

You are not asking Edit to do anything, so it is efficient and does nothing. You need to have something for Edit to do, for example .onMove or .onDelete. However adding these to your List(…) call will cause an error, as that is not a RandomAccessCollection, just a list type.

List(courseCategoryList, id: \.self, selection: $selectedItem) { category in
    Text(category)
        .font(.title3)
        .listRowBackground(RoundedRectangle(cornerRadius: 10).fill(Color.orange.opacity(0.2)))
}
.onDelete { courseCategoryList.remove(atOffsets: $0) }
.onMove { courseCategoryList.move(fromOffsets: $0, toOffset: $1) }
// .disabled(courseCategoryList.isEmpty)
.navigationTitle("Dev Techie")
.toolbar { EditButton() }

will fail to build

Try this instead.

List {
    ForEach(courseCategoryList, id: \.self) { category in
        Text(category)
            .font(.title3)
            .listRowBackground(RoundedRectangle(cornerRadius: 10).fill(Color.orange.opacity(0.2)))
    }
    .onDelete { courseCategoryList.remove(atOffsets: $0) }
    .onMove { courseCategoryList.move(fromOffsets: $0, toOffset: $1) }
}
.navigationTitle("Dev Techie")
.toolbar { EditButton() }

If you omit both the .onDelete and .onMove then pressing the Edit button will again do nothing.

1      

Hacking with Swift is sponsored by Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.