Удалить строку в виде таблицы в swift
Я пытаюсь удалить строку в виде таблицы. Я выполнил необходимые методы, но когда я прокручиваю строку по горизонтали, кнопка удаления не приходит. Я искал, и я нашел одно и то же решение повсюду, но он не работает в моем случае. Я не знаю, где я делаю ошибку. Кто-нибудь может мне помочь?
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if editingStyle == .Delete
{
dataHandler.deletePeripheral(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
Ответы
Ответ 1
Если ниже кодирование полезно для вас, я буду счастлив
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if editingStyle == .Delete
{
yourArray.removeAtIndex(indexPath.row)
self.tableView.reloadData()
}
}
SWIFT 3.0
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool
{
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
if editingStyle == .delete
{
yourArray.remove(at: indexPath.row)
tblDltRow.reloadData()
}
}
Необходимо обновить таблицу.
Ответ 2
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
self.tableView.beginUpdates()
self.arrayData.removeObjectAtIndex(indexPath.row) // also remove an array object if exists.
self.tableView.deleteRowsAtIndexPaths(NSArray(object: NSIndexPath(forRow: indexPath.row, inSection: 2)), withRowAnimation: UITableViewRowAnimation.Left)
self.tableView.endUpdates()
}
Ответ 3
Применить ограничения автоопределения к виду таблицы. Кнопка удаления есть, но не отображается из-за отсутствия макета
Ответ 4
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if editingStyle == UITableViewCellEditingStyle.Delete {
numbers.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
Ответ 5
Я тоже боролся с этим, но, наконец, нашел решение - я запускаю XCode 8.3.2. Многие ответы, которые я читал, были для более старых версий XCode/Swift, и многие из них были для Objective-C.
Решение, которое я нашел, это использовать инструмент editActionsForRowAt для UITableViews. Примечание. Все остальное, что я читал, постоянно указывало мне на инструмент "commit editingStyle" для UITableView, но я никогда не смог заставить его работать. Использование editActionsForRowAt отлично сработало для меня.
ПРИМЕЧАНИЕ: "postData" - это имя массива, к которому я добавил данные.
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action, IndexPath) in
// Remove item from the array
postData.remove(at: IndexPath.row)
// Delete the row from the table view
tableView.deleteRows(at: [IndexPath as IndexPath], with: .fade)
})
// set DeleteAction Button to RED (this line is optional - it simply allows you to change the color of the Delete button - remove it if you wish)
deleteAction.backgroundColor = UIColor.red
return [deleteAction]
}
У меня также есть код для добавления кнопки "EDIT" рядом с кнопкой "Удалить":
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let editAction = UITableViewRowAction(style: .default, title: "Edit", handler: { (action, IndexPath) in
//print("Edit tapped")
})
// Set EditAction button to blue (this line is not mandatory - it just sets the color of the Edit box to blue)
editAction.backgroundColor = UIColor.blue
let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action, IndexPath) in
//print("Delete tapped")
// Remove item from the array
postData.remove(at: IndexPath.row)
// Delete the row from the table view
tableView.deleteRows(at: [IndexPath as IndexPath], with: .fade)
})
// set DeleteAction Button to RED (this line isn't mandatory - it just sets the color of the Delete box)
deleteAction.backgroundColor = UIColor.green
return [editAction, deleteAction]
}
EDIT: фиксированный формат, поэтому код появился в сером поле:)
Ответ 6
для быстрого 3
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete {
dataHandler.deletePeripheral(indexPath.row)
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
// - OR -
// mTableView.reloadData() //mTableView is an outlet for the tableView
}
}
Ответ 7
Я знаю, что у вас есть. Я думаю, что вы просто проверяете свои ограничения таблиц, они могут быть неправильными, просто перепроверьте ваши ограничения макета
Ответ 8
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
yourArray.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
Ответ 9
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if editingStyle == .Delete
{
carsArray.removeAtIndex(indexPath.row)
self.tableView.reloadData()
}
}