繁体   English   中英

如何在Swift4的TableView单元格中使用按钮获取JSON ID

[英]How to get JSON id with button in tableview cell in swift4

我正在使用具有删除按钮名称的tableView单元格,我想从需要删除的tableView单元格中删除JSON数据,以便从JSON ID中删除Tableview的JSON数据。 indexPathdidSelect行函数中获取该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.

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