Reputation: 1473
I am trying to create a delegate function to reload a collection view in a different view controller on an event.
To this end i have defined a protocol, set the delegate in the class, and a simple delegate function.
protocol ReloadCollectionDelegate: class {
func reloadCollectionViewFromDelegate()
}
class JourneyViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UITabBarControllerDelegate, UIScrollViewDelegate, ReloadCollectionDelegate {
// delegate function from downloadCollectionController to relaod collection
func reloadCollectionViewFromDelegate() {
// simply call the reload function
reloadCollection()
}
And in my class that will be calling the above function:
// define the delegate for use
weak var reloadJourneyDelegate: ReloadCollectionDelegate?
// reload the collection view in JourneyViewController
let JVC = self.viewController.storyboard!.instantiateViewController(withIdentifier: "JourneyViewController") as! JourneyViewController
self.reloadJourneyDelegate = JVC
self.reloadJourneyDelegate?.reloadCollectionViewFromDelegate()
print(JVC):
JourneyViewController: 0x7fc7f7c55bf0
print(self) - from JourneyViewController (viewDidLoad):
JourneyViewController: 0x7fc7f7e2db10
So i am getting different instances of the same view controller.
How do i define this so i have the correct instance and can modify the UI?
Thanks
Upvotes: 1
Views: 686
Reputation: 551
this worked for me where as the above answer did not:
let JCV = UIStoryboard(name: "Main", bundle: nil)
.instantiateViewControllerWithIdentifier("JourneyViewController") as! JourneyViewController
The import part is that you have to add a storyboard ID in the identity inspector.
Upvotes: 0
Reputation: 188
This line creates a new instance of JourneyViewController
self.viewController.storyboard!.instantiateViewController(withIdentifier: "JourneyViewController") as! JourneyViewController
You must have a way to refer back to the original instance of JourneyViewController. Either by having a property that points to it or if both view controllers are in a hierarchy such that JourneyViewController
is the parent of another view controller:
class ViewControllerA: UIViewController {
override viewDidLoad() {
let button = UIButton(frame: CGRect(x: self.view.bounds.width/2, y: 400, width: 50, height: 50))
button.backgroundColor = UIColor.black
button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
self.view.addSubview(button)
}
func buttonPressed() {
let journey = self.parent as! JourneyViewController
journey.reloadCollection()
}
}
Upvotes: 1