Adicionar furto para excluir UITableViewCell

144

Estou fazendo um aplicativo CheckList com um UITableView. Eu queria saber como adicionar um furto para excluir um UITableViewCell.

Este é o meu ViewController.swift:

import UIKit

class ViewController: UIViewController,  UITextFieldDelegate, UITableViewDelegate,      UITableViewDataSource {

var tableView: UITableView!
var textField: UITextField!
var tableViewData:Array<String> = []

// Define Colors

let lightColor: UIColor = UIColor(red: 0.996, green: 0.467, blue: 0.224, alpha: 1)
let medColor: UIColor = UIColor(red: 0.973, green: 0.388, blue: 0.173, alpha: 1)
let darkColor: UIColor = UIColor(red: 0.800, green: 0.263, blue: 0.106, alpha: 1)
let greenColor: UIColor = UIColor(red: 0.251, green: 0.831, blue: 0.494, alpha: 1)

init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
    super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    // Custom initialization
}

override func viewDidLoad() {
    super.viewDidLoad()

    //Set up table view

    self.tableView = UITableView(frame: CGRectMake(0, 100, self.view.bounds.size.width, self.view.bounds.size.height-100), style: UITableViewStyle.Plain)
    self.tableView.registerClass(MyTableViewCell.self, forCellReuseIdentifier: "myCell")
    self.tableView.backgroundColor = darkColor
    //self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    self.tableView.delegate = self
    self.tableView.dataSource = self

    self.view.addSubview(self.tableView)

    //Set up text field

    self.textField = UITextField(frame: CGRectMake(0, 0, self.view.bounds.size.width, 100))
    self.textField.backgroundColor = lightColor
    self.textField.font = UIFont(name: "AvenirNext-Bold", size: 26)
    self.textField.delegate = self

    self.view.addSubview(self.textField)



}

//Table View Delegate

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {

    return tableViewData.count

}

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {

    var myNewCell: MyTableViewCell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as MyTableViewCell
    myNewCell.text = self.tableViewData[indexPath.row]

    return myNewCell

}

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {

    let mySelectedCell:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)

    //Colors

    mySelectedCell.detailTextLabel.textColor = UIColor.whiteColor()
    mySelectedCell.tintColor = UIColor.whiteColor()

    //Setup Details / Date

    let myDate:NSDate = NSDate()
    var myDateFormatter:NSDateFormatter = NSDateFormatter()
    myDateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle

    mySelectedCell.detailTextLabel.text = myDateFormatter.stringFromDate(myDate)
    mySelectedCell.accessoryType = UITableViewCellAccessoryType.Checkmark
    mySelectedCell.backgroundColor = greenColor

}

override func prefersStatusBarHidden() -> Bool {
    return true

}

//Text Field Delegate

func textFieldShouldReturn(textField: UITextField!) -> Bool {

    tableViewData.append(textField.text)
    textField.text = ""
    self.tableView.reloadData()
    textField.resignFirstResponder()
    return true

}

}

E este é MyTableViewCell.swift:

import UIKit

class MyTableViewCell: UITableViewCell {

let medColor: UIColor = UIColor(red: 0.973, green: 0.388, blue: 0.173, alpha: 1)

init(style: UITableViewCellStyle, reuseIdentifier: String) {
    super.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)

    self.textColor = UIColor.whiteColor()
    self.backgroundColor = medColor
    self.selectionStyle = UITableViewCellSelectionStyle.None
}

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

}

Estou usando o iOS8 como destino de implantação (não tenho certeza da diferença que isso fará).

jdnoon
fonte
2
Por favor, leia o "Guia de programação de exibição de tabela para iOS". Há uma seção inteira sobre como lidar com exclusões de exibição de tabela. Estão faltando vários métodos de delegação necessários para fazê-lo funcionar.
rmaddy
3
FYI - metade do código que você postou é irrelevante para a pergunta. Poste apenas o código relevante.
rmaddy

Respostas:

316

Adicione estas duas funções:

func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.Delete) {
        // handle delete (by removing the data from your array and updating the tableview)
    }
}

Swift 3.0:

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.delete) {
        // handle delete (by removing the data from your array and updating the tableview)
    }
}

Swift 4.2

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == .delete) {
        // handle delete (by removing the data from your array and updating the tableview)
    }
}
Traço
fonte
3
Programador iniciante para iOS aqui - existe uma boa maneira de aprender quais métodos precisam ser implementados para lidar com (aparentemente) funcionalidades básicas como essa? A documentação parece um pouco detalhada e difícil de seguir para os meus novatos.
lase
4
@datayeah se você quiser alterar o texto do botão "Excluir", é possível substituir essa função, func tableView (tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? {// retorne o texto que você deseja adicionar aqui}
Rachel
1
O código swift 3 não possui um colchete de fechamento }. Levei 5 minutos para descobrir isso: p
Ibrahim
1
@lase Você pode dar uma olhada em um aplicativo chamado Dash. Ele permite que você pesquise a documentação e é muito mais rápido do que navegar na web. Também é armazenado localmente no seu computador, para que você não precise de acesso à Web para procurar informações. Você também pode carregar a documentação para outros idiomas.
Adrian
1
@lase, a API do iOS é preenchida com tantas coisas que seria praticamente impossível saber tudo. Por mais clichê que pareça, você aprende coisas como essa por experiência própria. Tenho vindo a fazer iOS por 6 anos e estou aqui apenas como você, porque eu esqueci como adicionar Swipe excluir: ^)
anon_nerd
30

Você pode tentar isso:

func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
    return true
}

func tableView(tableView: UITableView!, commitEditingStyle editingStyle:   UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
    if (editingStyle == UITableViewCellEditingStyle.Delete) {
        NamesTable.beginUpdates()
        Names.removeAtIndex(indexPath!.row)
        NamesTable.deleteRowsAtIndexPaths([indexPath], withRowAnimation: nil)
        NamesTable.endUpdates()

    }
}
ANIL.MUNDURU
fonte
2
Obrigado por beingUpdates()e endUpdates(). Você não os vê frequentemente e acabei de ver que eles faziam parte da palestra sobre as melhores práticas da WWDC.
precisa saber é o seguinte
Obrigado por isso!! : D
Dark Innocence
27

Outra maneira que permite alterar o texto de "Excluir" e adicionar mais botões ao deslizar uma célula é usar editActionsForRowAtIndexPath.

func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}

func tableView(tableView: (UITableView!), commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: (NSIndexPath!)) {

}

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {

    var deleteAction = UITableViewRowAction(style: .Default, title: "Delete") {action in
       //handle delete
    }

    var editAction = UITableViewRowAction(style: .Normal, title: "Edit") {action in
        //handle edit
    }

    return [deleteAction, editAction]
}

canEditRowAtIndexPathe commitEditingStyleainda são necessários, mas você pode deixar em commitEditingStylebranco porque a exclusão é realizada editActionsForRowAtIndexPath.

keverly
fonte
1
Teve que mudar a assinatura da última função para `func tableView (tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]?` Mas, caso contrário, funcionou. Obrigado!
Crashalot
1
@Crashalot Se sua classe é herdada UITableViewControllere você está substituindo esse método, sim, a assinatura deve retornar [UITableViewRowAction]?. No entanto, quando você não está herdando UITableViewController, é quando o método deve retornar [AnyObject]?. Pensei em esclarecer quando usar qual, para quem lê isso não está apenas adivinhando.
keverly
16
    import UIKit

    class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource
    {
      var items: String[] = ["We", "Heart", "Swift","omnamay shivay","om namay bhagwate vasudeva nama"]
        var cell : UITableViewCell
}




    @IBOutlet var tableview:UITableView

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }




    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return self.items.count;
    }


    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {

        var cell = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell

        if !cell {
            cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL")}



        cell!.textLabel.text = self.items[indexPath.row]

        return cell
        }
    func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
        return true
    }

    func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
        if (editingStyle == UITableViewCellEditingStyle.Delete) {
            // handle delete (by removing the data from your array and updating the tableview)


            if let tv=tableView
            {



             items.removeAtIndex(indexPath!.row)
                tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)



        }
    }
}


}
VARUN SINGHAL
fonte
10

É novo recurso no iOS11 e Swift 4.

Link de referência:

Deslize à direita:

@available(iOS 11.0, *)
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let delete = UIContextualAction(style: .destructive, title: "Delete") { (action, sourceView, completionHandler) in
        print("index path of delete: \(indexPath)")
        completionHandler(true)
    }

    let rename = UIContextualAction(style: .normal, title: "Edit") { (action, sourceView, completionHandler) in
        print("index path of edit: \(indexPath)")
        completionHandler(true)
    }
    let swipeActionConfig = UISwipeActionsConfiguration(actions: [rename, delete])
    swipeActionConfig.performsFirstActionWithFullSwipe = false
    return swipeActionConfig
}

insira a descrição da imagem aqui

Bhadresh
fonte
8

use-o :

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
        langData.removeAtIndex(indexPath.row) //langData is array from i delete values
        tableView.deleteRowsAtIndexPaths([indexPath],  withRowAnimation: UITableViewRowAnimation.Automatic)
    }
}

espero que ajude você

Subhash Sharma
fonte
6

Swift 4 - @ disponível (iOS 11.0, *)

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let edit = UIContextualAction(style: .normal, title: "") { (action, view, nil) in
        let refreshAlert = UIAlertController(title: "Deletion", message: "Are you sure you want to remove this item from cart? ", preferredStyle: .alert)

        refreshAlert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action: UIAlertAction!) in

        }))

        refreshAlert.addAction(UIAlertAction(title: "No", style: .default, handler: { (action: UIAlertAction!) in
            refreshAlert .dismiss(animated: true, completion: nil)
        }))

        self.present(refreshAlert, animated: true, completion: nil)
    }
    edit.backgroundColor = #colorLiteral(red: 0.3215686275, green: 0.5960784314, blue: 0.2470588235, alpha: 1)
    edit.image = #imageLiteral(resourceName: "storyDelete")
    let config = UISwipeActionsConfiguration(actions: [edit])
    config.performsFirstActionWithFullSwipe = false
    return config
}
steffi pravasi
fonte
5

Swift 3:

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.delete) {
        // delete data and row
        dataList.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
    }
}
Hong Duan
fonte
Alguma idéia de como posso alterar o botão excluir para dizer cancelado?
Alec.
se você deseja alterar o texto do botão "Excluir", é possível substituir essa função, func tableView (tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? {// retorne o texto que você deseja adicionar aqui} # Rachel
Bista
5

Swift 3 com título personalizado suportado

        func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
                return true
            }

    //If you want to change title
            func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
                return "Cancel"
            }

            func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
                if (editingStyle == UITableViewCellEditingStyle.delete) {
// you might want to delete the item at the array first before calling this function
                    tableView.deleteRows(at: indexPath, with: .automatic)
                }
            }
Basil Mariano
fonte
5

Eu usei o tableViewCell para mostrar vários dados; depois de deslizar () da direita para a esquerda em uma célula, ele mostrará dois botões. leva um argumento. insira a descrição da imagem aqui

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let Approve = UITableViewRowAction(style: .normal, title: "Approve") { action, index in

        self.ApproveFunc(indexPath: indexPath)
    }
    Approve.backgroundColor = .green

    let Reject = UITableViewRowAction(style: .normal, title: "Reject") { action, index in

        self.rejectFunc(indexPath: indexPath)
    }
    Reject.backgroundColor = .red



    return [Reject, Approve]
}

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func ApproveFunc(indexPath: IndexPath) {
    print(indexPath.row)
}
func rejectFunc(indexPath: IndexPath) {
    print(indexPath.row)
}
Akbar Khan
fonte
'UITableViewRowAction' está obsoleto no iOS 13. Você precisa usar 'UIContextualAction'!
Jarish Jose
4

A partir do Xcode 6.1.1, existem algumas pequenas alterações na resposta do Dash.

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }

    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if (editingStyle == UITableViewCellEditingStyle.Delete) {
            // handle delete (by removing the data from your array and updating the tableview)
        }
    }
TimWhiting
fonte
4

Funciona para mim no Swift 2.0

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

}

override func tableView(tableView: UITableView,
    editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
    let block = UITableViewRowAction(style: .Normal, title: "Block") { action, index in
        print("Block")
        self.removeObjectAtIndexPath(indexPath, animated: true)
    }
    let delete = UITableViewRowAction(style: .Default, title: "Delete") { action, index in
        print("Delete")
        self.removeObjectAtIndexPath(indexPath, animated: true)
    }
    return [delete, block]
}
Tristan.Liu
fonte
Você pode, por favor, elaborar mais sobre o que "Block"faz?
nyxee
4

No Swift 4 tableview adicionar, deslize para excluir UITableViewCell

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let delete = UITableViewRowAction(style: .destructive, title: "delete") { (action, indexPath) in
        // delete item at indexPath

    }
    return [delete]
}
Pratik Lad
fonte
3
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]?
{

    let delete = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "DELETE"){(UITableViewRowAction,NSIndexPath) -> Void in

        print("What u want while Pressed delete")
    }
    let edit = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "EDIT"){(UITableViewRowAction,NSIndexPath) -> Void in

        print("What u want while Pressed Edit")
    }

    edit.backgroundColor = UIColor.blackColor()
    return [delete,edit]
}
Piyush Sanepara
fonte
2

Swift 4

@available(iOS 11.0, *)    
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
            let action =  UIContextualAction(style: .normal, title: "", handler: { (action,view,completionHandler ) in
                //do stuff
                completionHandler(true)
                let data:NSDictionary = self.conversations[indexPath.row] as! NSDictionary
                print(data)
                let alert:UIAlertController = UIAlertController(title: "", message: "are you sure want to delete ?", preferredStyle: .alert)

                alert.addAction(UIAlertAction(title: "CANCEL", style: UIAlertActionStyle.cancel, handler: { (action) in
                }))
                self.present(alert, animated: true, completion: nil)
            })
            action.image = UIImage(named: "")
            action.backgroundColor = UIColor(red: 0/255, green: 148/255, blue: 204/255, alpha: 1.0)
            let confrigation = UISwipeActionsConfiguration(actions: [action])

            return confrigation
        }
Vishal Vaghasiya
fonte
2

Basta adicionar o método:

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let delete = UITableViewRowAction(style: UITableViewRowActionStyle.destructive, title: "Delete") { (action, indexPath) in
        self.arrayFruit.remove(at: indexPath.row)
        self.tblList.reloadData()
    }

    let edit = UITableViewRowAction(style: UITableViewRowActionStyle.normal, title: "Edit") { (action, indexpath) in

        let alert = UIAlertController(title: "FruitApp", message: "Enter Fuit Name", preferredStyle: UIAlertControllerStyle.alert)
        alert.addTextField(configurationHandler: { (textField) in
            textField.placeholder = "Enter new fruit name"
        })
        alert.addAction(UIAlertAction(title: "Update", style: UIAlertActionStyle.default, handler: { [weak alert](_) in
            let textField = alert?.textFields![0]
            self.arrayFruit[indexPath.row] = (textField?.text!)!
            self.tblList.reloadData()
        }))

        self.present(alert, animated: true, completion: nil)
    }
    edit.backgroundColor = UIColor.blue
    return [delete,edit]
}

insira a descrição da imagem aqui

Mr.Javed Multani
fonte
1

aqui Veja meu resultado Swift com botão totalmente personalizável suportado

Bônus antecipado por usar essa implementação de apenas um método e você obtém um botão perfeito !!!

 func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let action = UIContextualAction(
            style: .destructive,
            title: "",
            handler: { (action, view, completion) in

                let alert = UIAlertController(title: "", message: "Are you sure you want to delete this incident?", preferredStyle: .actionSheet)

                alert.addAction(UIAlertAction(title: "Delete", style: .destructive , handler:{ (UIAlertAction)in
                    let model = self.incedentArry[indexPath.row] as! HFIncedentModel
                    print(model.incent_report_id)
                    self.incedentArry.remove(model)
                    tableView.deleteRows(at: [indexPath], with: .fade)
                    delete_incedentreport_data(param: ["incent_report_id": model.incent_report_id])
                    completion(true)
                }))

                alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:{ (UIAlertAction)in
                    tableView.reloadData()
                }))

                self.present(alert, animated: true, completion: {

                })


        })
        action.image = HFAsset.ic_trash.image
        action.backgroundColor = UIColor.red
        let configuration = UISwipeActionsConfiguration(actions: [action])
        configuration.performsFirstActionWithFullSwipe = true
        return configuration
}
Paresh Mangukiya
fonte
1
Eu amo isso, mas como eu poderia excluir uma célula usando isso?
Evelyn
1
Basta implementar esse método na classe como método delegado tableview e remover no índice da sua fonte de dados (matriz ya model) assim: - deixe model = self.incedentArry [indexPath.row] as! HFIncedentModel self.incedentArry.remove (modelo)
Paresh Mangukiya
0

SWIFT 3 - UIViewController

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.delete) {
        // handle delete (by removing the data from your array and updating the tableview)
        print("delete tableview cell")
    }
}
BennyTheNerd
fonte
0

rápido 3

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

    return true
}

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

    if (editingStyle == UITableViewCellEditingStyle.delete) {

        arrayCityName.remove(at: indexPath.row)
        self.tableCityName.reloadData()
    }
}
Deepak Tagadiya
fonte
0

basta adicioná-los, assumindo que sua matriz de dados é 'data'

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.delete) {
        // handle delete (by removing the data from your array and updating the tableview)
        if let tv=table
        {



            data.remove(at: indexPath.row)
            tv.deleteRows(at: [indexPath], with: .fade)



        }
    }
}
Hatim
fonte
0
func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {

  let share = UITableViewRowAction(style: .normal, title: "Share") { action, index in
    //handle like delete button
    print("share button tapped")
  }

  share.backgroundColor = .lightGray

  let delete = UITableViewRowAction(style: .normal, title: "Delete") { action, index in
    self.nameArray.remove(at: editActionsForRowAt.row)
    self.swipeTable.beginUpdates()
    self.swipeTable.deleteRows(at: [editActionsForRowAt], with: .right)
    self.swipeTable.endUpdates()

    print("delete button tapped")
  }

  delete.backgroundColor = .orange
  return [share,delete]
}

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
  return true
}
MehdiNasiriPoor
fonte
0
@available(iOS 11.0, *)
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

        let editAction = UIContextualAction.init(style: UIContextualAction.Style.normal, title: "Edit", handler: { (action, view, completion) in
            //TODO: Edit
            completion(true)
            self.popUpViewPresent(index:indexPath.row)
        })

        let deleteAction = UIContextualAction.init(style: UIContextualAction.Style.destructive, title: "Delete", handler: { (action, view, completion) in
            //TODO: Delete
            completion(true)
            self.deleteTagAction(senderTag:indexPath.row)
        })
        editAction.image = UIImage(named: "Edit-white")
        deleteAction.image = UIImage(named: "Delete-white")
        editAction.backgroundColor = UIColor.gray
        deleteAction.backgroundColor = UIColor.red

        let config = UISwipeActionsConfiguration(actions: [deleteAction, editAction])
        config.performsFirstActionWithFullSwipe = false
        return config
    }
Sai kumar Reddy
fonte
0

Swift 5

Como UITableViewRowAction foi descontinuado no iOS 13.0, você pode usar UISwipeActionsConfiguration

   func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let deleteAction = UIContextualAction(style: .destructive, title: "Delete") {  (contextualAction, view, boolValue) in
            self.deleteData(at: indexPath)
        }

        let editAction = UIContextualAction(style: .normal, title: "Edit") {  (contextualAction, view, boolValue) in
            self.editData(at: indexPath)
        }
        editAction.backgroundColor = .purple
        let swipeActions = UISwipeActionsConfiguration(actions: [deleteAction,editAction])

        return swipeActions
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func deleteData(at indexPath: IndexPath) {
        print(indexPath.row)
    }

    func editData(at indexPath: IndexPath) {
        print(indexPath.row)
    }

Rashid Latif
fonte