我有一个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")
}
}
在我的ViewController in cellForRowAt indexPath中,我有以下代码
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)
}
}
答案 0 :(得分:0)
您可以将其分为2个不同的事件或
class CODetailsTicketCell: UITableViewCell {
var onButtonTapped: ((_ sender: UIButton) -> Void)? = nil
@IBAction func firstBtnTapped(_ sender: UIButton) {
if let onButtonTapped = self.onButtonTapped {
onButtonTapped?(sender)
}
print("First button was pressed")
}
@IBAction func secondBtnTapped(_ sender: UIButton) {
if let onButtonTapped = self.onButtonTapped {
onButtonTapped(sender)
}
print("Second button was pressed")
}
}
在onButtonTapped
的作业中,如果您使用[weak self]
来避免保留周期,请务必添加self
。
cell.onButtonTapped = { [weak self] sender in
if sender.tag == 1 {
// Do something
} else {
// Do other thing
}
}