添加滑动以删除UITableViewCell

 草原华子无敌_531 发布于 2023-01-11 10:04

我正在使用一个CheckList应用程序UITableView.我想知道如何添加滑动来删除a UITableViewCell.

这是我的ViewController.swift:

import UIKit

class ViewController: UIViewController,  UITextFieldDelegate, UITableViewDelegate,      UITableViewDataSource {

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

// 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作为部署目标(不确定它将产生的差异).

7 个回答
  • 这是iOS11和Swift 4的新功能.

    参考链接:

    尾随滑动:

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

    在此输入图像描述

    2023-01-11 10:05 回答
  • 你可以试试这个:

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

    2023-01-11 10:05 回答
  • 用它 :

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

    希望它能帮助你

    2023-01-11 10:05 回答
  • 支持自定义标题的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)
                    }
                }
    

    2023-01-11 10:05 回答
  • 另一种允许您更改"删除"文本并在滑动单元格时添加更多按钮的方法是使用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]
    }
    

    canEditRowAtIndexPath并且commitEditingStyle仍然是必需的,但是您可以commitEditingStyle在处理删除时留空editActionsForRowAtIndexPath.

    2023-01-11 10:05 回答
  •     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)
    
    
    
            }
        }
    }
    
    
    }
    

    2023-01-11 10:05 回答
  • 添加这两个功能:

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

    2023-01-11 10:06 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有