[英]How to get JSON id with button in tableview cell in swift4
I'm using tableView
cell with button name of delete and I want to delete my JSON data from tableView
cell I need to so That JSON ID to delete the JSON data from my Tableview
. 我正在使用具有删除按钮名称的
tableView
单元格,我想从需要删除的tableView
单元格中删除JSON数据,以便从JSON ID中删除Tableview
的JSON数据。 I'm using to get the JSON ID for that indexPath
in didSelect
row function. 我
indexPath
在didSelect
行函数中获取该indexPath
的JSON ID。 but the problem is I can't get JSON Id from that indexPath
without pressing the row. 但是问题是我不按该行就无法从该
indexPath
获取JSON ID。
var selectedList: JSONList?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedList = JSONList[indexPath.row]
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? TableviewCell
cell?.Numbers.text = JSONList[indexPath.row].Number
cell?.Trash.addTarget(self, action: #selector(Deleting), for: .touchUpInside)
cell?.selectionStyle = .none
return cell!
}
//here is my delete function calling
func Deleting() {
let selectedListObj = selectedList
print(selectedListObj!.id)
}
First of all set a tag to the button which it will be in your case the row of the IndexPath
, add this code in cellForRowAt
: 首先,为按钮设置一个标记,在您的情况下,该
IndexPath
将位于IndexPath
的行中,并将此代码添加到cellForRowAt
:
cell?.Trash.addTarget(self, action: #selector(deleting(_:)), for:
.touchUpInside)
cell?.Trash.tag = indexPath.row
You need to modify the deleting()
function to be @objc
since selectors after swift 3+ are a must to add that and add the button as param into it: 您需要将
@objc
deleting()
函数修改为@objc
因为必须在swift 3+之后添加选择器并将其作为参数添加到其中:
@objc private func deleting(_ button:UIButton){
// here you got the object
let selectedObject = JSONList[button.tag]
}
use closure to get the tapped buttons cells indexpath. 使用闭包获取被点击的按钮单元格的indexpath。
update the table view cell with ibaction and call the closure whenever tapping on trash button. 使用ibaction更新表格视图单元格,并在每次点击垃圾箱按钮时调用闭包。
class FakeTableCell: UITableViewCell{
var selectedCell: ((UITableViewCell) -> ())?
@IBAction func trashButtonTapped(){
selectedCell?(self)
}
}
then we can get the indexpath of the cell in cell for row for indexpath as follows 那么我们就可以为索引路径的行获取单元格中单元格的索引路径,如下所示
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = FakeTableCell()
cell.selectedCell = { selectedCell in
if let ip = tableView.indexPathForRow(at: selectedCell.center){
self.deleteData(with: ip.row)
}
}
return cell
}
func deleteData(with row: Int){
// get the object by JSONList[row]
let item = JSONList[row]
// perform deletion
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.