我有一个表视图,其单元格中有一个按钮,这些按钮应打开具有唯一ID的视图。因此,我需要将参数传递给我的按钮,但是使用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)
}
是否有任何方法可以将带有某些参数的操作转介给按钮?谢谢大家:)
您可以尝试将委托函数添加到您的自定义uitaiteViewCell。
例如,我在此自定义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)
符合控制器,当然可以实现我的tableViewCell的委托功能。
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
}
}
也许您可以尝试将您的按钮链接到@ibaction并使用params [indexpath.row]。
获得IndexPath:
var cell = sender.superview() as? UITableViewCell
var indexPath: IndexPath? = yourTableView.indexPath(for: cell!)