ChatGPT解决这个技术问题 Extra ChatGPT

添加滑动删除 UITableViewCell

我正在制作一个带有 UITableView 的 CheckList 应用程序。我想知道如何添加滑动以删除 UITableViewCell

这是我的 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

}

}

这是 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
}

}

我使用 iOS8 作为部署目标(不确定它会产生什么不同)。

请阅读“iOS 表视图编程指南”。有一整节是关于处理表视图删除的。您缺少几个必需的委托方法来使其工作。
仅供参考 - 您发布的一半代码与问题无关。请仅发布相关代码。

G
Giovanni Palusa

添加这两个函数:

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)
    }
}

斯威夫特 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)
    }
}

斯威夫特 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)
    }
}

新手 iOS 程序员在这里 - 有没有一种很好的方法来学习需要实现哪些方法来处理(看似)这样的基本功能?对于我的新手来说,文档似乎有点冗长且难以理解。
@datayeah 如果你想改变“删除”按钮文本,你可以重写这个函数, func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? { //返回要在此处添加的文本 }
swift 3 代码缺少右大括号 }。我总共花了 5 分钟才弄清楚这一点:p
@lase 您可能想看一下名为 Dash 的应用程序。它使您能够搜索文档,并且比浏览网络要快得多。它还本地存储在您的计算机上,因此您无需访问网络即可查找内容。您还可以加载其他语言的文档。
@lase iOS API 充满了很多东西,几乎不可能全部了解。因此,听起来很陈词滥调,你从经验中学到了这样的东西。我已经做 iOS 6 年了,我和你一样在这里,因为我忘记了如何添加 Swipe to Delete :^)
O
OhadM

你可以试试这个:

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()

    }
}

如果您支持 iOS11+,请参阅 discussion

尽可能使用 performBatchUpdates(_:completion:) 方法而不是这个方法。


感谢beingUpdates()endUpdates()。你不会经常看到它们,我只是看到它们是 WWDC 最佳实践演讲的一部分。
这次真是万分感谢!! :D
k
keverly

另一种允许您在滑动单元格时更改“删除”文本并添加更多按钮的方法是使用 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]
}

canEditRowAtIndexPathcommitEditingStyle 仍然是必需的,但您可以将 commitEditingStyle 留空,因为删除是在 editActionsForRowAtIndexPath 中处理的。


必须将最后一个函数的签名更改为 func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]?谢谢!
@Crashalot 如果您的类继承自 UITableViewController 并且您正在覆盖此方法,那么是的,签名必须返回 [UITableViewRowAction]?。但是,当您不是从 UITableViewController 继承时,即该方法应返回 [AnyObject]?。以为我会弄清楚何时使用 which 所以任何阅读本文的人都不仅仅是在猜测。
B
Bhadresh

这是 iOS11 和 Swift 4 中的新功能。

Reference link :

尾随滑动:

@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
}

https://i.stack.imgur.com/QjGPX.png


R
Rajesh
    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)



        }
    }
}


}

S
Subhash Sharma

用它 :

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)
    }
}

希望对你有帮助


A
Akbar Khan

https://i.stack.imgur.com/L8FTU.png

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)
}

“UITableViewRowAction”在 iOS 13 中已弃用。您需要改用“UIContextualAction”!
L
Leena

Swift 4 -- @available(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
}

T
TimWhiting

从 Xcode 6.1.1 开始,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)
        }
    }

H
Hong Duan

斯威夫特 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)
    }
}

知道如何将删除按钮更改为取消吗?
如果你想改变“删除”按钮的文字,你可以重写这个函数,func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? { //返回您要在此处添加的文本 } #Rachel
B
Basil Mariano

支持自定义标题的 Swift 3

        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)
                }
            }

T
Tristan.Liu

在 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]
}

您能否详细说明 "Block" 的作用?
P
Piyush Sanepara
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]
}

P
Pratik Lad

在 Swift 4 tableview 中添加,滑动删除 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]
}

R
Rashid Latif

斯威夫特 5

由于 UITableViewRowAction 在 iOS 13.0 中已弃用,因此您可以使用 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)
    }



E
Eric Aya

斯威夫特 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
        }

M
Mr.Javed Multani

只需添加方法:

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]
}

https://i.stack.imgur.com/MPySw.jpg


u
user3810914

https://i.stack.imgur.com/XBwKO.png

/*
     SWIPE to Action
     */
    
    func tableView(_ tableView: UITableView,
                   editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .none
    }
    // Right Swipe
    func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        
        let action = UIContextualAction(style: .normal,
                                        title: "Favourite") { [weak self] (action, view, completionHandler) in
                                            self?.handleMarkAsFavourite()
                                            completionHandler(true)
        }
        action.backgroundColor = .systemBlue
        
        return UISwipeActionsConfiguration(actions: [action])
    }
    
    func tableView(_ tableView: UITableView,
                       trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        // Archive action
        let archive = UIContextualAction(style: .normal,
                                         title: "Archive") { [weak self] (action, view, completionHandler) in
                                            self?.handleMoveToArchive()
                                            completionHandler(true)
        }
        archive.backgroundColor = .systemGreen

        // Trash action
        let trash = UIContextualAction(style: .destructive,
                                       title: "Trash") { [weak self] (action, view, completionHandler) in
            self?.handleMoveToTrash(book: (self?.books![indexPath.row]) as! BookItem)
                                        completionHandler(true)
        }
        trash.backgroundColor = .systemRed

        // Unread action
        let unread = UIContextualAction(style: .normal,
                                       title: "Mark as Unread") { [weak self] (action, view, completionHandler) in
                                        self?.handleMarkAsUnread()
                                        completionHandler(true)
        }
        unread.backgroundColor = .systemOrange

        let configuration = UISwipeActionsConfiguration(actions: [trash, archive, unread])
        // If you do not want an action to run with a full swipe
        configuration.performsFirstActionWithFullSwipe = false
        return configuration
    }
    
    
    
    private func handleMarkAsFavourite() {
        print("Marked as favourite")
    }

    private func handleMarkAsUnread() {
        print("Marked as unread")
    }

    private func handleMoveToTrash(book: BookItem) {
        print("Moved to trash")
        print(book)
        let alert = UIAlertController(title: "Hi!", message: "Bạn có muốn xóa \(book.name)", preferredStyle: .alert)
            
             let ok = UIAlertAction(title: "Xóa", style: .default, handler: { action in
                book.delete()
                self.listBook.reloadData()
             })
             alert.addAction(ok)
             let cancel = UIAlertAction(title: "Hủy", style: .default, handler: { action in
             })
             alert.addAction(cancel)
             DispatchQueue.main.async(execute: {
                self.present(alert, animated: true)
        })
        
    }

    private func handleMoveToArchive() {
        print("Moved to archive")
    }

B
BennyTheNerd

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")
    }
}

D
Deepak Tagadiya

迅速 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()
    }
}

H
Hatim

假设您的数据数组是“数据”,只需添加这些

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)



        }
    }
}

P
Piotr Pradzynski
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
}

S
Sai kumar Reddy
@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
    }

M
Maddy

Xcode 要求 UIContextualAction,这对我来说对更新版本有用:

对于尾随滑动操作:->

 func delete(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
        let company = companies[indexPath.row]
        let action = UIContextualAction(style: .destructive, title: "Delete") { (action, view, _) in
           // Perform Delete Action
        }
        return action
    }
    
    func edit(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
        let action  = UIContextualAction(style: .normal, title: "Edit") { (action, view, escaping) in
            // Perform Edit Action
        }
        return action
    }
    
    override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let delete = self.delete(forRowAtIndexPath: indexPath)
        let edit = self.edit(forRowAtIndexPath: indexPath)
        let swipe = UISwipeActionsConfiguration(actions: [delete, edit])
        return swipe
    }

对于领先的滑动操作:->

 func delete(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
        let company = companies[indexPath.row]
        let action = UIContextualAction(style: .destructive, title: "Delete") { (action, view, _) in
           // Perform Delete Action
        }
        return action
    }
    
    func edit(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
        let action  = UIContextualAction(style: .normal, title: "Edit") { (action, view, escaping) in
            // Perform Edit Action
        }
        return action
    }
    
    override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let delete = self.delete(forRowAtIndexPath: indexPath)
        let edit = self.edit(forRowAtIndexPath: indexPath)
        let swipe = UISwipeActionsConfiguration(actions: [delete, edit])
        return swipe
    }

为 tableView 委托的 canEditRowAt 返回 true:->

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

关注公众号,不定期副业成功案例分享
关注公众号

不定期副业成功案例分享

领先一步获取最新的外包任务吗?

立即订阅