假设我有两个名为 A 和 B 的 View Controller 。在我的 View Controller B 中有一个 TableView 。当我在我的表格 View 中选择一个单元格时,我想将该信息传递回 A。
我有一本字典,内容如下:
myData = [String: DataModel]
其中 DataModel 采用以下形式
struct DataModel{
var address = ""
var name = ""
}
我想将 B 中所选单元格的 key 发送回 A。我应该怎么做?
谢谢你的帮助
最佳答案
在
class BViewController 之前添加:
protocol ClassBViewControllerDelegate: class { func didSelectTableViewCell(onRow row: Int) }
在
BViewController
中创建委托(delegate)属性:weak var delegate: ClassBViewControllerDelegate?
实现 tableView 委托(delegate)方法
tableView(_:didSelectRowAt:)
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) { let row = indexPath.row delegate?.didSelectTableViewCell(onRow: row) }
告诉
ClassAViewController
它符合ClassBViewControllerDelegate
这样的:class ClassAViewController: UIViewController, ClassBViewControllerDelegate {
将
ClassAViewController
和ClassBViewController
绑定(bind)到ClassAViewController
中的适当位置,例如,prepareForSegue:sender:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "SegueIdentifierXYZ" { if let vc = segue.destination as? ClassBViewController { vc.delegate = self } } }
在
ClassAViewController
中使用委托(delegate)方法didSelectTableViewCell(onRow row: Int)
委托(delegate)契约(Contract)ClassBViewControllerDelegate
:func didSelectTableViewCell(onRow row: Int) { print("Selected table view row is:", row) }
关于swift - 如何正确地将数据从一个 View Controller 的选定单元格传递到前一个 View Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51701029/