What is the correct way to delete an entry from a list? Where should the closure be placed?
#ObservedObject var category : Category
var body: some View {
List {
ForEach(category.reminders?.allObjects as! [Reminder]) { reminder in
NavigationLink(destination: ReminderDetail(reminder: reminder)) {
VStack {
Text(reminder.title!)
}
}
}
}
.navigationTitle("Reminders")
VStack {
NavigationLink(destination: AddReminder(category: category)) { Text("Add Reminder") }
}.padding()
}
You can try this:
var body: some View {
List {
ForEach(category.reminders?.allObjects as! [Reminder]) { reminder in
NavigationLink(destination: ReminderDetail(reminder: reminder)) {
VStack {
Text("reminder.title!")
}
}
}.onDelete(perform: self.deleteItem)
}
.navigationTitle("Reminders")
private func deleteItem(at indexSet: IndexSet) {
self.category.reminders(atOffsets: indexSet)
}
Related
This is annoying. The Edit button in the NavigationBar pushes the View twice. I made a test button which behaves correctly doing the same thing:
import SwiftUI
struct DetailListPage: View {
#Environment(\.presentationMode) var presentationMode
var listName: ListNames
// #State private var isEditDetailListPageShowing = false
#State private var selection: String? = nil
var body: some View {
Form {
Section(header: Text(listName.title ?? "")
.font(.title)
.padding()) {
Text(listName.listDetail ?? "Nothing is set yet!")
.multilineTextAlignment(.leading)
.padding()
.cornerRadius(12)
}
NavigationLink(destination: EditDetailListPage(listName: listName)) {
Button {
} label: {
Text("Edit Page")
}
}
}
.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
self.presentationMode.wrappedValue.dismiss()
} label: {
Text("Cancel")
} .padding()
//Edit List Detail
}
ToolbarItem(placement: .navigationBarTrailing) {
NavigationLink(
destination: EditDetailListPage(listName: listName)) {
Text("Edit")
}
}
}
}
The Text("Edit") right above is pushing the view twice.
The Button above it acts correctly. Would like to use the navigationbaritem instead of the button.
Works well for me, on macos 11.4, xcode 12.5, target ios 14.5 and macCatalyst 11.3.
Probably some other code (or settings/system) that is causing the issue.
What system are you using? Show us the missing code and how you call the views. Let us know if the test code below does not work for you.
This is the test code I used:
#main
struct TestErrorApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct EditDetailListPage: View {
var listName: [String]
var body: some View {
Text("EditDetailListPage")
}
}
struct ContentView: View {
var body: some View {
NavigationView {
DetailListPage(listName: ["test var"])
}.navigationViewStyle(StackNavigationViewStyle())
}
}
struct DetailListPage: View {
#Environment(\.presentationMode) var presentationMode
var listName: [String]
// #State private var isEditDetailListPageShowing = false
#State private var selection: String? = nil
var body: some View {
Form {
Section(header: Text("header string")
.font(.title)
.padding()) {
Text("Nothing is set yet!")
.multilineTextAlignment(.leading)
.padding()
.cornerRadius(12)
}
NavigationLink(destination: EditDetailListPage(listName: listName)) {
Button {
} label: {
Text("Edit Page")
}
}
}
.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
self.presentationMode.wrappedValue.dismiss()
} label: {
Text("Cancel")
} .padding()
//Edit List Detail
}
ToolbarItem(placement: .navigationBarTrailing) {
NavigationLink(
destination: EditDetailListPage(listName: listName)) {
Text("Edit")
}
}
}
}
}
struct ListFrontPage: View {
#Environment(\.presentationMode) var presentationMode
#Environment(\.managedObjectContext) var managedObjectContext
#State private var isAddNewListShowing = false
var listNames: FetchRequest<ListNames>
init() {
listNames = FetchRequest<ListNames>(entity: ListNames.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \ListNames.sort, ascending: true)], animation: .default)
}
var body: some View {
VStack {
List() {
Text("Accounts")
.frame(maxWidth: .infinity)
.font(.system(size: 30, weight: .heavy, design: .default))
ForEach (listNames.wrappedValue) { listName in
NavigationLink(destination: DetailListPage(listName: listName)) {
Text("\(listName.title ?? "")")
}
}
.onDelete(perform: deleteItems)
.onMove(perform: moveItem)
}
Spacer()
ZStack {
NavigationLink(destination: AddNewList()) {
Image(systemName: "plus.circle.fill").font(.system(size: 64))
}
}
}
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading: Button {
self.presentationMode.wrappedValue.dismiss()
} label: {
Image(systemName: "chevron.backward")
Label("Back", image: "")
}, trailing: EditButton())
.navigationBarTitle(Text("Account Management"))
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { listNames.wrappedValue[$0] }.forEach(CoreDataHelper.sharedManager.deleteItems)
}
}
private func moveItem(from offsets: IndexSet, to destination: Int)
{
print("From: \(String(describing: offsets)) To: \(destination)")
// Make an array of items from fetched results
var revisedItems: [ ListNames ] = listNames.wrappedValue.map{ $0 }
// change the order of the items in the array
revisedItems.move(fromOffsets: offsets, toOffset: destination )
// update the userOrder attribute in revisedItems to
// persist the new order. This is done in reverse order
// to minimize changes to the indices.
for reverseIndex in stride( from: revisedItems.count - 1,
through: 0,
by: -1 )
{
revisedItems[ reverseIndex ].sort =
Int16( reverseIndex )
}
}
}
I’m seeing this issue where a Form / NavigationLink set up seems to stop passing through the data on changes.
Expected behavior: Checkmarks should update when you pick a different food.
Observed behavior: You can see the favorite food changing outside the NavigationLink Destination, but not inside.
This setup mirrors a dynamic application where a ForEach is used to display various NavigationLinks in the Form based on parent data. Weirdly enough, this works if you replace Form with VStack, so I’m curious why this isn’t updating.
I have attached two minimum-setup example projects that replicate this issue where the destination of a NavigationLink is not receiving an update when data is changing. One with Binding, one with simpler passed properties.
Sample Project #1 with Binding - Dropbox
Sample Project #2 without Binding - Dropbox
Code #1:
//
// ContentView.swift
// Form Updating Example
//
// Created by Sahand Nayebaziz on 12/10/20.
//
import SwiftUI
struct ContentView: View {
#State var isPresentingMainView = false
#State var favoriteFood: FoodType = .bagel
var body: some View {
VStack {
Button(action: { isPresentingMainView = true }, label: {
Text("Present Main View")
})
}
.fullScreenCover(isPresented: $isPresentingMainView) {
MainView(favoriteFood: $favoriteFood)
}
}
}
struct MainView: View {
#Binding var favoriteFood: FoodType
var body: some View {
NavigationView {
HStack {
Spacer()
Text(favoriteFood.emoji)
.font(.title)
.foregroundColor(.secondary)
Spacer()
NavigationView {
Form {
List {
ForEach(["SomethingRepresentingShowingFood"], id: \.self) { _ in
NavigationLink(
destination: makeDetail(),
label: {
Text("Food Randomizer")
})
}
}
}
}
.navigationViewStyle(StackNavigationViewStyle())
.frame(maxWidth: 350)
}
.navigationTitle("Main")
.navigationBarTitleDisplayMode(.inline)
}
.navigationViewStyle(StackNavigationViewStyle())
}
func makeDetail() -> some View {
Form {
ForEach(FoodType.allCases) { foodType in
Button(action: { favoriteFood = foodType }, label: {
HStack {
Text(foodType.emoji)
Spacer()
if favoriteFood == foodType {
Image(systemName: "checkmark")
}
}
})
}
}
}
}
enum FoodType: String, Identifiable, CaseIterable {
case bagel, pizza, broccoli
var id: String { rawValue }
var emoji: String {
switch self {
case .bagel: return "🥯"
case .pizza: return "🍕"
case .broccoli: return "🥦"
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
Group {
ContentView()
MainView(favoriteFood: .constant(.bagel))
MainView(favoriteFood: .constant(.bagel))
.makeDetail()
}
}
}
Code #2:
//
// ContentView.swift
// Form Updating Example
//
// Created by Sahand Nayebaziz on 12/10/20.
//
import SwiftUI
struct ContentView: View {
#State var isPresentingMainView = false
#State var favoriteFood: FoodType = .bagel
var body: some View {
VStack {
Button(action: { isPresentingMainView = true }, label: {
Text("Present Main View")
})
}
.fullScreenCover(isPresented: $isPresentingMainView) {
MainView(currentFavoriteFood: favoriteFood, onUpdateFavoriteFood: { favoriteFood = $0 })
}
}
}
struct MainView: View {
let currentFavoriteFood: FoodType
let onUpdateFavoriteFood: (FoodType) -> Void
var body: some View {
NavigationView {
HStack {
Spacer()
Text(currentFavoriteFood.emoji)
.font(.title)
.foregroundColor(.secondary)
Spacer()
NavigationView {
Form {
List {
ForEach(["SomethingRepresentingShowingFood"], id: \.self) { _ in
NavigationLink(
destination: makeDetail(),
label: {
Text("Food Randomizer")
})
}
}
}
}
.navigationViewStyle(StackNavigationViewStyle())
.frame(maxWidth: 350)
}
.navigationTitle("Main")
.navigationBarTitleDisplayMode(.inline)
}
.navigationViewStyle(StackNavigationViewStyle())
}
func makeDetail() -> some View {
Form {
ForEach(FoodType.allCases) { foodType in
Button(action: { onUpdateFavoriteFood(foodType) }, label: {
HStack {
Text(foodType.emoji)
Spacer()
if currentFavoriteFood == foodType {
Image(systemName: "checkmark")
}
}
})
}
}
}
}
enum FoodType: String, Identifiable, CaseIterable {
case bagel, pizza, broccoli
var id: String { rawValue }
var emoji: String {
switch self {
case .bagel: return "🥯"
case .pizza: return "🍕"
case .broccoli: return "🥦"
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
Group {
ContentView()
MainView(currentFavoriteFood: .bagel, onUpdateFavoriteFood: { _ in })
MainView(currentFavoriteFood: .bagel, onUpdateFavoriteFood: { _ in })
.makeDetail()
}
}
}
I am trying to create a list that only allows users to delete after entering an editing mode. I attempted to try using ternary operation in the onDelete modifier but was unable to figure it out. Any recommendations?
Here is my code:
struct ContentView: View {
#State private var stuff = ["First", "Second", "Third"]
#State private var check = false
var body: some View {
Form {
Button(action: { check.toggle() }, label: { Text(check ? "Editing" : "Edit") })
ForEach(0..<stuff.count) { items in
Section{ Text(stuff[items]) }
}
.onDelete(perform: self.deleteItem)
}
}
private func deleteItem(at indexSet: IndexSet) {
self.stuff.remove(atOffsets: indexSet)
}
}
I assume you look for the following
var body: some View {
Form {
Button(action: { check.toggle() }, label: { Text(check ? "Editing" : "Edit") })
ForEach(0..<stuff.count) { items in
Section{ Text(stuff[items]) }
}
.onDelete(perform: self.deleteItem)
.deleteDisabled(!check) // << this one !!
}
}
struct ContentView: View {
#State private
var stuff = ["First", "Second", "Third"]
var body: some View {
NavigationView {
Form {
ForEach(0..<stuff.count) { item in
Section {
Text(stuff[item])
}
}
.onDelete(
perform: delete)
}
.navigationBarItems(
trailing:
EditButton()
)
.navigationTitle("Test")
}
}
}
extension ContentView {
private func delete(at indexSet: IndexSet) {
stuff.remove(atOffsets: indexSet)
}
}
This can be done directly within the .onDelete method, using the ternary operator:
.onDelete(perform: check ? deleteItem : nil)
This situation is no problem.enter link description here
So I'm confused, I don't know if this is a bug or whether Apple designed it this way.
struct HomePage: View {
var body: some View {
NavigationView {
VStack {
jumpView1
.padding()
.background(Color.red)
.padding()
jumpView2
.padding()
.background(Color.blue)
}
.navigationBarItems(leading:leftBarItem)
.navigationBarTitle("Home",displayMode: .inline)
}
}
var leftBarItem: some View {
NavigationLink(destination: CustomViewController()) {
Text("Go CustomViewController ")
}
}
var jumpView1: some View {
NavigationLink(destination: CustomViewController()) {
Text("Go CustomViewController")
.foregroundColor(.white)
}
}
var jumpView2: some View {
NavigationLink(destination: SecondPage()) {
Text("Go SecondPage")
.foregroundColor(.white)
}
}
}
struct FirstPage: View {
var body: some View {
NavigationLink(destination: CustomViewController()) {
Text("Go CustomViewController")
}
}
}
struct SecondPage: View {
var body: some View {
NavigationLink(destination: CustomViewController()) {
Text("Go CustomViewController")
}
}
}
the func dismantleUIViewController only call in leftBarItem Action,
and never call, when push in body NavigatinLink
struct CustomViewController: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> CustomRealViewController {
let vc = CustomRealViewController()
return vc
}
func updateUIViewController(_ uiViewController: CustomRealViewController, context: Context) {
}
static func dismantleUIViewController(_ uiViewController: CustomRealViewController, coordinator: Coordinator) {
print("dismiss")
}
}
the func deinit only call in leftBarItem Action,
and never call, when push in body NavigatinLink
class CustomRealViewController: UIViewController {
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print("viewDidDisappear")
}
deinit {
print("deinit")
}
}
I took an example from this question: How does one enable selections in SwiftUI's List and edited the code to be able to delete rows one by one. But I don't know how to delete multiple rows from list.
Could you help me, please?
var demoData = ["Phil Swanson", "Karen Gibbons", "Grant Kilman", "Wanda Green"]
struct ContentView : View {
#State var selectKeeper = Set<String>()
var body: some View {
NavigationView {
List(selection: $selectKeeper){
ForEach(demoData, id: \.self) { name in
Text(name)
}
.onDelete(perform: delete)
}
.navigationBarItems(trailing: EditButton())
.navigationBarTitle(Text("Selection Demo \(selectKeeper.count)"))
}
}
func delete(at offsets: IndexSet) {
demoData.remove(atOffsets: offsets)
}
}
solution from SwiftUI how to perform action when EditMode changes?
struct Item: Identifiable {
let id = UUID()
let title: String
static var i = 0
init() {
self.title = "\(Item.i)"
Item.i += 1
}
}
struct ContentView: View {
#State var editMode: EditMode = .inactive
#State var selection = Set<UUID>()
#State var items = [Item(), Item(), Item()]
var body: some View {
NavigationView {
List(selection: $selection) {
ForEach(items) { item in
Text(item.title)
}
}
.navigationBarTitle(Text("Demo"))
.navigationBarItems(
leading: editButton,
trailing: addDelButton
)
.environment(\.editMode, self.$editMode)
}
}
private var editButton: some View {
Button(action: {
self.editMode.toggle()
self.selection = Set<UUID>()
}) {
Text(self.editMode.title)
}
}
private var addDelButton: some View {
if editMode == .inactive {
return Button(action: addItem) {
Image(systemName: "plus")
}
} else {
return Button(action: deleteItems) {
Image(systemName: "trash")
}
}
}
private func addItem() {
items.append(Item())
}
private func deleteItems() {
for id in selection {
if let index = items.lastIndex(where: { $0.id == id }) {
items.remove(at: index)
}
}
selection = Set<UUID>()
}
}
extension EditMode {
var title: String {
self == .active ? "Done" : "Edit"
}
mutating func toggle() {
self = self == .active ? .inactive : .active
}
}