【问题标题】:How to edit row of cell?如何编辑单元格行?
【发布时间】:2017-12-10 02:23:42
【问题描述】:

我无法在单元格的第一行打开编辑模式。我尝试了这段代码,但没有帮助。

   public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
            if indexPath.row == 1{
                return true
            }
            return false
        }

有人可以帮我吗?

【问题讨论】:

  • 第一行表示:indexPath.row == 0,它是从零开始的...

标签: swift row cell editing


【解决方案1】:

首先,确保您已添加UITableViewDataSource 协议。其次,您可能还需要以下实现。

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let myAction = UITableViewRowAction(style: .normal, title: "MY_ACTION") { (action, indexPath) in
        print("I'm here")
    }

    return [myAction]
}

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

}

【讨论】:

    【解决方案2】:

    如果你想编辑第一行然后替换

    if indexPath.row == 1 
    

    if indexPath.row == 0 
    

    因为indexPath.row 从 0 开始,而不是从 1。

    希望这会有所帮助。

    编辑:

    由于您没有显示完整的代码,我在这里添加示例代码。

    查看以下代码:

    import UIKit
    
    class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
        @IBOutlet weak var tbl: UITableView!
    
        let arr = ["1", "2", "3"]
    
        override func viewDidLoad() {
            super.viewDidLoad()
            tbl.dataSource = self
            tbl.delegate = self
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = self.tbl.dequeueReusableCell(withIdentifier: "cell")!
    
            cell.textLabel?.text = self.arr[indexPath.row]
    
            return cell
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return arr.count
        }
    
        func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    
            //set 0 for first cell
            if indexPath.row == 0 {
                return true
            }
            return false
        }
    
        //Need this method for delete cell
        func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    
            if editingStyle == UITableViewCellEditingStyle.delete {
                tbl.reloadData()
            }
        }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-07
    • 1970-01-01
    • 2017-12-23
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 2011-08-26
    相关资源
    最近更新 更多