0

我正在尝试使用按钮删除选定的行。因此我需要 indexPath.row,我将值写入全局变量,但是当我在按钮中访问它时,它返回 nil 给我。

var selectedRow = ""

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let selectedEvent = myConversationRows[indexPath.row]
    selectedRow = selectedEvent.id!
}

@IBAction func cancelConversation(_ sender: Any) {

    print("selected")
    print(self.selectedRow)
}

我猜当我点击按钮 didSelectRowAt 时不会触发。我尝试了不同的方法,但它们都不起作用。

4

2 回答 2

2

不要使用全局变量!!!

她是解决这个问题的简单方法:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "YOURE_CELL_ID", for: indexPath) as? YOUT_CELL_CLASS {
        cell.youreButton.tag = indexPath.row
    }
}

和:

@IBAction func cancelConversation(_ sender: Any) {
    if let btn = sender as? UIButton {
        let row = btn.tag
        tableView.deleteRows(at: [IndexPath(row: row, section: 0)], with: .bottom)
    }
}

为什么你不使用 ios 删除滑动手势?

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        print("Deleted")


        self.tableView.deleteRows(at: [indexPath], with: .automatic)
    }
}
于 2018-07-17T13:08:52.430 回答
1

您应该声明selectedRow为 anInt并为其分配一个默认值,-1意思是“未设置”。然后,输入tableView(_:didSelectRowAt:)这一行:

selectedRow = indexPath.row

cancelConversation()这个:

if selectedRow != -1 {
    //...
}
于 2018-07-17T12:58:16.083 回答