[英]How to get JSON id with button in tableview cell in swift4
我正在使用具有刪除按鈕名稱的tableView
單元格,我想從需要刪除的tableView
單元格中刪除JSON數據,以便從JSON ID中刪除Tableview
的JSON數據。 我indexPath
在didSelect
行函數中獲取該indexPath
的JSON ID。 但是問題是我不按該行就無法從該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)
}
首先,為按鈕設置一個標記,在您的情況下,該IndexPath
將位於IndexPath
的行中,並將此代碼添加到cellForRowAt
:
cell?.Trash.addTarget(self, action: #selector(deleting(_:)), for:
.touchUpInside)
cell?.Trash.tag = indexPath.row
您需要將@objc
deleting()
函數修改為@objc
因為必須在swift 3+之后添加選擇器並將其作為參數添加到其中:
@objc private func deleting(_ button:UIButton){
// here you got the object
let selectedObject = JSONList[button.tag]
}
使用閉包獲取被點擊的按鈕單元格的indexpath。
使用ibaction更新表格視圖單元格,並在每次點擊垃圾箱按鈕時調用閉包。
class FakeTableCell: UITableViewCell{
var selectedCell: ((UITableViewCell) -> ())?
@IBAction func trashButtonTapped(){
selectedCell?(self)
}
}
那么我們就可以為索引路徑的行獲取單元格中單元格的索引路徑,如下所示
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.