数据不会传回之前的 tableview controller

Data will not pass back to previous tableview controller

当我点击后退按钮时,试图将 TableViewController 2 上选定单元格上的标签传递回 TableViewController 1 上静态单元格上的标签。我在 didSelectRowAtIndexPath() 得到了正确的标签。但是当我尝试打印时,数据不会传回。我尝试了很多场景,最后才来到这里。如有任何帮助,我们将不胜感激!

tableviewcontroller一:

class SearchTableViewController: UITableViewController, SortProtocol {

 var sort: String?

 override func viewDidLoad() {
    super.viewDidLoad(

  SORTBYCELL.detailTextLabel?.text = sort


} 
  func passdata(sort: String?){
    self.sort = (sort)
  }

TableViewController 二:

protocol SortProtocol {
func passdata(sort: String?)
 }
 class SortByTable: UITableViewController {

var delegate: SortProtocol?

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
}

 override func tableView(tableView: UITableView,         didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let current = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell

    let sort = current.textLabel!.text!

    self.delegate?.passdata(sort)

如果您检查过 delegate 不是 nil(例如,通过在其上设置断点),您的代码不会提及。

更新 UITableViewCells 时的最佳选择是通过数据源方法:

func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

因此,在您的情况下,passdata 使用新值 sort 更新您的数据源,然后调用 tableView.reloadData() 重新加载单元格。

您必须分配代表。如果您有一个 "back" 按钮,我将假设您使用的是导航控制器。使用它,我们得到对第一个 viewController 的引用。因此,您在 SortByTable 中的 viewDidLoad() 将如下所示:

override func viewDidLoad() {
    super.viewDidLoad()

    let searchVC = self.navigationController?.viewControllers[0] as! SearchTableViewController
    self.delegate = searchVC

    tableView.delegate = self
}