UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.