Brennen Berkley Brennen Berkley - 2 months ago 14
Swift Question

Swift: Assign delegate class when delegator class isn't a direct child?

I am making an app that uses a set of drill-down tables, each with their own TableViewController, so my storyboard is set up with a MainViewController that has a segue to a TableViewController (MainTable) which has a segue to another TableViewController (SubTable). I created a protocol and now I'm trying to assign the SubTable as the delegator and MainTable as the delegate. All of the solutions I've found only work when the delegator is called (or segued to) directly from the delegate class, in which case you can use

SubTable.delegate = self
in the prepareForSegue method, but that doesn't work if SubTable is called(created) from within the delegate class (MainView). Sorry if this is confusing, I will be happy to clarify any of it. Here is an example of what I want:

class MainViewController: UIViewController, delegate {
override func viewDidLoad() {
super.viewDidLoad()
SubTable.delegate = self //Doesn't work
}

func acceptData(data: String!) {
print(data)
}
}


the SubTable.delegate = self line doesn't work because SubTable hasn't been created yet, but if I create it beforehand using something like
let instance = SubTable()
and then
instance.delegate = self
then it still dines't work because the segue from MainTable to SubTable creates a new, separate instance of SubTable.

protocol delegate {
func acceptData(data: String!)
}

class MainTable: UITableViewController {

}

class SubTable: UITableViewController {
var delegate: delegate?

func sendData() {
self.delegate?.acceptData(data: "some text")
}
}

Answer

You may pass your delegate to the MainTable and assign it there when creating SubTable. Create a field in your MainTable to store it

var subTableDelegate : delegate?

in MainViewController:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destinationVC = segue.destination as! MainTable
    destinationVC.subTableDelegte = self
}

in MainTable:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destinationVC = segue.destination as! SubTable
    destinationVC.delegate = self.subTableDelegate
}
Comments