【发布时间】:2017-12-11 03:30:04
【问题描述】:
我有一个 TableView,我在其中显示所有数据,每个单元格可能有 1-2 个按钮。我阅读了许多主题并了解如何通过我的 ViewController 为每个按钮添加目标。由于这些按钮将被转发到同一个VC并显示图像,我有以下代码。在我的 TableViewCell 子类中,我有 2 个按钮
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
为了通过 segue 传递数据,我在 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)
}
}
【问题讨论】:
标签: ios swift uitableview segue