Search code examples
swiftuitableviewxcode7.3

Data will not pass back to previous tableview controller


Trying to pass the label on selected cell on TableViewController Two back to a label on a static cell on TableViewController one when i hit the back button. Im getting the correct label at the didSelectRowAtIndexPath(). but the data will not pass back when i try to print it. I've tried numerous scenarios and came here as a last resort. any help would be appreciated thank you!

tableviewcontroller one:

class SearchTableViewController: UITableViewController, SortProtocol {

 var sort: String?

 override func viewDidLoad() {
    super.viewDidLoad(

  SORTBYCELL.detailTextLabel?.text = sort


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

TableViewController Two:

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)

Solution

  • You have to assign the delegate. If you have a "back" button, I'm going to then assume you're using a navigation controller. Using that, we get a reference to the first viewController. Thus, your viewDidLoad() in SortByTable will look like:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let searchVC = self.navigationController?.viewControllers[0] as! SearchTableViewController
        self.delegate = searchVC
    
        tableView.delegate = self
    }