magellan
magellan

Reputation: 63

Swift: Protocol and Delegates passing data to previous view controller

I am working in Swift and the function categoryPressedFunction is not being called.

Protocol:

protocol categoryPressed: class { //1 create a protocol with function that passes a string
    func categoryPressedFunction(category: String)
}

View Controller 2:

//set the delegate
weak var delegate: categoryPressed?

//when cell is selected in tableview, grab the "category" which is a string and then dismiss
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let category = guideCategoryArray[indexPath.row] // gets category
    delegate?.categoryPressedFunction(category: category) // sets delegate to know it was pressed
    self.presentingViewController?.dismiss(animated: true, completion: nil) //dismisses
}
}

View Controller 1 (Previous)

//set class delegate
...categoryPressed

//add function that sets label to category and looks up items based off category
func categoryPressedFunction(category: String) {
    print("categoryPressedFunctionPressed")
    resourceArray.removeAll()
    resourceLabel.text = category
    getItems(item: category, { [self] in
        print("got new items for \(category) and refreshed the tableview")
        self.resourceTableView.reloadData()
    })
}

When returning to ViewController 1, nothing happens. The tableview does not reload, nor does the label change to the category pressed. Am I missing something?

Upvotes: 0

Views: 469

Answers (2)

Harish Singh
Harish Singh

Reputation: 765

You might have missed assigning delegate to self while moving from VC1 to VC2.

Hope below code helps you.

//Some Navigation logic 
let VC2 = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "VC2Identifier") as! VC2;
VC2.delegate = self
self.present(VC2, animated: true, completion: nil)

Upvotes: 0

Luca Sfragara
Luca Sfragara

Reputation: 644

Delegates might be nil. Did you add this line in the ViewDidLoad method?

delegate = self

Upvotes: 1

Related Questions