繁体   English   中英

UITableView编辑模式不显示删除按钮

[英]UITableView edit mode not showing delete button

我正在从Apple复制样本Food Tracker应用程序,并且遇到一个问题,即在“编辑”模式下我的TableView中的项目不显示左手删除图标(红色的圆形)。 如果我向左滑动,则会在右侧显示一个删除按钮。 我已经下载了Food Tracker代码,它可以正常工作。

我可以看到的区别是示例应用程序已实现了UITableViewController,而我在标准UIViewController中具有UITableView。 我不确定为什么这行不通。

有一些类似的问题,但是它们是Swift / Ios的旧版本,因此我不确定它们是否仍然有用。

这是到示例应用程序的链接https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/index.html#//apple_ref/doc/uid/TP40015214-CH2-SW1

这是我最近添加的可使其正常工作的功能

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

    return true
}

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

    if editingStyle == .delete {
    //delete the row from the dataSource
        dataSource.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)

    }
    else if editingStyle == .insert {
    //create a new instance and insert the row

    }

}

并将其添加到ViewDidLoad()以在导航栏中获得“编辑”按钮

 navigationItem.leftBarButtonItem = editButtonItem

这是Food Tracker示例的外观;

在此处输入图片说明

我的缺少左手按钮。 我可以看到的唯一区别是,我在ViewController中使用了TableView。

谢谢

缺口

我想我解决了这个问题。 实际上,UITableViewController正在做的工作有很多“魔术”。 要在具有TableView的普通UIViewController中重新创建此控件,必须重写SetEditing函数,并基于按钮的标题将其置于编辑模式。

override func setEditing(_ editing: Bool, animated: Bool) {


    let status = navigationItem.leftBarButtonItem?.title



    if status == "Edit" {

        tableView.isEditing = true

        navigationItem.leftBarButtonItem?.title = "Done"

        }

    else {

        tableView.isEditing = false

        navigationItem.leftBarButtonItem?.title = "Edit"

    }

}

无需检查barButtonItem的标题,因为点击它已经切换了它的状态并在编辑参数时传递了正确的状态。

同样,在覆盖时,您需要调用super的实现,因为不存在将始终显示delete指示符。

override func setEditing(_ editing: Bool, animated: Bool) {
    super.setEditing(editing, animated: true)
    tableView.setEditing(editing, animated: true)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM