mor*_*itz 0 tableview swift swift3 ios10
我已经使用Swift 3构建了一个简单的toDoList应用。现在,我希望能够TableView
通过从右向左滑动来删除我的商品。这是我找到的代码。但是当我向左滑动时,什么也没有发生。
码:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return toDoList.count
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")
cell.textLabel?.text = toDoList[indexPath.row]
return cell
}
//
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
toDoList.remove(at: indexPath.row)
UserDefaults.standard.set(toDoList, forKey: "toDoList")
tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return .delete
}
Run Code Online (Sandbox Code Playgroud)
这仍然行不通。当我向左滑动时,什么也没有发生。待办事项列表本身正在工作。我可以将项目添加到表中,但不能删除它们。
谢谢 :)
您是否实现了tableView:canEditRowAtIndexPath:方法?
附:斯威夫特3。
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
Run Code Online (Sandbox Code Playgroud)
编辑:
感谢@rmaddy记住的默认值tableView:canEditRowAtIndexPath:
是true
,实现它不能解决问题。
我不太确定您要从代码段中执行什么操作,因此请确保您正在实现以下方法(UITableViewDelegate):
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
toDoList.remove(at: indexPath.row)
UserDefaults.standard.set(toDoList, forKey: "toDoList")
tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return .delete
}
Run Code Online (Sandbox Code Playgroud)
您还可以保留tableView:canEditRowAtIndexPath:
方法的实现:
要求数据源验证给定的行是否可编辑。
因此,例如,如果要让第一行不可编辑,即用户无法滑动并删除第一行,则应执行以下操作:
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if indexPath.row == 0 {
return false
}
return true
}
Run Code Online (Sandbox Code Playgroud)
另外,请确保UITableViewDataSource
和UITableViewDelegate
与ViewController连接。
希望这会有所帮助。
归档时间: |
|
查看次数: |
3631 次 |
最近记录: |