在具有多个表视图的视图控制器中删除 UITableView 行 (Swift)

Delete UITableView Rows in View Controller with multiple tableviews (Swift)

我正在尝试在我的 viewcontroller 中包含多个 UITableView 的表视图之一中实现删除行。我的数组使用 NSUserDefaults 保存。 这是我的代码,但我收到错误 Index out of range 如果有人想测试它,这里也是我的项目的 link:https://files.fm/f/wv9uerhn

 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == .delete {

    if tableView == ScheduleTableView{

       // Here is my code but it gives me an error, first you need to add a row with the add button

        let defaults = UserDefaults.standard
        var myarray = defaults.stringArray(forKey: "ScheduleArray") ?? [String]()

        print(myarray)
        myarray.remove(at: indexPath.row)
        ScheduleTableView.deleteRows(at: [indexPath], with: .fade)


    }

    if tableView == GoalsTableView{



    }
  }
}

您实际上并没有将包含已删除记录的数组保存到 UserDefaults。将您的代码更新为

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
{
        if editingStyle == .delete {

        if tableView == ScheduleTableView{

           // Here is my code but it gives me an error, first you need to add a row with the add button

            let defaults = UserDefaults.standard
            var myarray = defaults.stringArray(forKey: "ScheduleArray") ?? [String]()

            print(myarray)
            myarray.remove(at: indexPath.row)
            defaults.set(myarray, forKey: "ScheduleArray")
            ScheduleTableView.deleteRows(at: [indexPath], with: .fade)


        }

        if tableView == GoalsTableView{



        }
    }
  }
}

希望这对您有所帮助。快乐编码。