I have a class that I want to receive data from a custom subclass of UIPageViewController
. For this purpose, I have defined a protocol as normal in the class I want to receive the information:
protocol GetMyIndexDelegate: class {
func getIndex()
}
class LandingPageViewController: UIViewController, GetMyIndexDelegate {
func getIndex() {
print("IT GOT CALLED")
}}
and then in the class which is to send the information:
class pageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
weak var delegate2: GetMyIndexDelegate?
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if (completed && finished) {
if let currentVC = pageViewController.viewControllers?.last {
let index = vcArr.index(of: currentVC)
delegate2?.getIndex()
}
}
}
I had to use delegate2
here because there is already a delegate UIPageViewControllerDelegate
and if I use delegate
I get an error
'cannot overide property with type UIPageViewControllerDelegate'
However when I run the app and scroll through the pages, the function getIndex
is not called.
I'm not sure if you can even have 2 delegates within the same class. I can't see another way of running the getIndex
function each time the page is scrolled and the index changes.
I suspect delegate2
is nil at the line where you try to call getIndex
. Since delegate2
is a weak
property, it will not keep an object alive. If you don't have some other strong reference to the object, then it will be deallocated and set the delegate2
property to nil.