WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

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      

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.