您需要从实现UITableViewCell 的UIViewController 执行此操作:
假设您有一个数组来填充您的 UITableView,代码将类似于:
import UIKit
class FirstViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var addresses = [String]()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showAddressDetail" {
if let secondViewController = segue.destination as? SecondViewController {
secondViewController.address = sender as! String
}
}
}
}
extension FirstViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.addresses.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: YourTableViewCell = tableView.dequeueReusableCell(withIdentifier: "YourTableViewCell", for: indexPath) as! YourTableViewCell
cell.address = self.addresses[indexPath.row]
cell.delegate = self
return cell
}
由于您必须通过UITableViewCell 上的按钮触发的操作调用您的函数,因此您可以在您的单元格上实现一个协议:
import UIKit
protocol YourTableViewCellDelegate: class {
func selectedAddress(address: String)
}
class YourTableViewCellDelegate: UITableViewCell {
weak var delegate: YourTableViewCellDelegate?
var address: String
}
在您的按钮操作中,像这样调用您的委托方法:
@IBAction func selectAddress() {
self.delegate?.selectedAddress(address: self.address)
}
这将触发您的UIViewController 上的委托。要处理调用,不要忘记将您的单元委托分配给您的视图控制器并在您的控制器中实现您的单元委托:
extension FirstViewController: YourTableViewCellDelegate {
func selectedAddress(address: String) {
// Do stuff with the selected address
}
}