我有一个 TableView ,它的单元格本身有一个按钮,这些按钮应该打开一个具有唯一 ID 的 View 。因此,我需要向按钮传递一个参数,但使用 addTarget
属性,我可以调用不带任何参数的函数。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
cell.editButton.addTarget(self, action: #selector(goToEdit(id:)), for: .touchUpInside)
}
func goToEdit(id: String) {
let edit = EditAdViewController(editingAdId: id)
self.navigationController?.pushViewController(edit, animated: true)
}
有什么方法可以将带有某些参数的操作引用到按钮吗?谢谢大家:)
最佳答案
您可以尝试向自定义 UITableViewCell 添加委托(delegate)函数。
例如,我在此自定义 tableViewCell 中有一个按钮:
PickupTableViewCell.swift
import UIKit
protocol PickupTableViewCellDelegate: NSObjectProtocol {
func pickupTableViewCell(userDidTapPickup pickup: Pickup, pickupTableViewCell: PickupTableViewCell)
}
class PickupTableViewCell: UITableViewCell {
// MARK: - Properties
@IBOutlet private weak var label_UserFullName: UILabel!
....
// MARK: - Functions
// MARK: IBAction
@IBAction func pickup(_ sender: Any) {
self.delegate?.pickupTableViewCell(userDidTapPickup: self.pickup, pickupTableViewCell: self)
}
}
然后,我通过 UITableViewDataSource (cellForRow)
来符合我的 Controller ,当然还实现了我的 tableViewCell 的委托(delegate)功能。
HomeViewController.swift
// MARK: - UITableViewDataSource
extension HomeViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let pickupTVC = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.pickupTableViewCell)!
pickupTVC.delegate = self
pickupTVC.pickup = self.pickups[indexPath.section]
return pickupTVC
}
}
// MARK: - PickupTableViewCellDelegate
extension HomeViewController: PickupTableViewCellDelegate {
func pickupTableViewCell(userDidTapPickup pickup: Pickup, pickupTableViewCell: PickupTableViewCell) {
// Do something
}
}
关于swift - 在 TableView 单元格中添加按钮目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46384309/