1
我有一個TableView,我顯示我的所有數據,每個單元格可能有1-2個按鈕。我閱讀了很多主題,並瞭解如何通過ViewController爲每個按鈕添加目標。由於這些按鈕將被轉發到相同的VC和顯示圖像,我有以下代碼。在我的TableViewCell子類我有2個按鈕通過數據取決於tableView中的按鈕單元格
class CODetailsTicketCell: UITableViewCel {
var onButtonTapped: (() -> Void)? = nil
@IBAction func firstBtnTapped(_ sender: UIButton) {
if let onButtonTapped = self.onButtonTapped {
onButtonTapped()
}
print("First button was pressed")
}
@IBAction func secondBtnTapped(_ sender: UIButton) {
if let onButtonTapped = self.onButtonTapped {
onButtonTapped()
}
print("Second button was pressed")
}
}
在我在cellForRowAt indexPath的ViewController我有以下代碼
let message = messages[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: "COTicketsCell", for: indexPath) as? CODetailsTicketCell {
cell.configureCell(openTickets: message)
cell.onButtonTapped = {
self.performSegue(withIdentifier: "toImageVC", sender: message)
}
return cell
爲了通過賽格瑞我使用以下代碼中prepareForSegue
傳遞數據override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toImageVC" {
let navigationController = segue.destination as? UINavigationController
if let targetController = navigationController?.topViewController as? ImageVC {
if let data = sender as? OpenTicketsData {
targetController.loadImageURL = URL(string: data.firstImageUrl)
}
}
}
}
一切正常工作,但我無法檢查prepareForSegue中的按鈕標記。基本上,目前這兩個按鈕發送相同的數據
targetController.loadImageURL = URL(string: data.firstImageUrl)
如何通過按下按鈕傳遞數據?我試圖做這樣的事情,但似乎是錯誤的,不工作。
let button = sender as? UIButton
if let data = sender as? OpenTicketsData {
if button?.tag == 1 {
targetController.loadImageURL = URL(string: data.firstImageUrl)
} else if button?.tag == 2 {
targetController.loadImageURL = URL(string: data.secondImageUrl)
}
}
非常感謝您的快速回復,但請詳細解釋它將如何解決問題?我沒有檢查,但我不想複製和粘貼代碼。 – Sargot
由於您已經爲您的2個按鈕設置了'tag',並且您爲它們使用了相同的事件,因此在'onButtonTapped'中,您需要將按鈕(發件人)作爲參數傳遞。通過這樣做,當您在視圖控制器中分配實際功能時,您知道哪個按鈕已被點擊。 – Lawliet
是的,我明白如何檢查cellForIndexPath中的標記,這對於爲多個按鈕執行不同的操作不是問題。問題是,我不知道如何在prepareForSegue中做到這一點,以顯示基於按鈕的數據。 – Sargot