kye
kye

Reputation: 2246

UICollectionView scrollToItemAtIndex after button action executed

When the currentViewController is popped I want to scroll the UICollectionView in the mainViewController to the index of the item which the currentViewController was currently at. I've tried implementing this in viewWillDisappear of the currentViewController but nothing happens when the back button action is executed.

   override func viewWillDisappear(animated : Bool) {
        super.viewWillDisappear(animated)
        if (self.isMovingFromParentViewController()){
            let parent = parentViewController as! UINavigationController
            let child = parent.childViewControllers[0] as! MainViewController
            child.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: currentIndex, inSection: 0), atScrollPosition: .Top, animated: true)
        }
    }

Upvotes: 0

Views: 98

Answers (3)

kye
kye

Reputation: 2246

Ended up created a protocol which was a lot more manageable that writtig everything in the viewWillDisappear of the childVC. Thank you André Slotta for the suggestion.

protocol CurrentIndexDelegate{
    func setCurrentIndex(index: Int?)
}

class ChildViewController: UIViewController{
    var currentIndexDelegate : CurrentIndexDelegate? = nil
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        if currentIndexDelegate != nil {
            currentIndexDelegate!.setCurrentIndex(currentIndex)
        }
    }
}

class MainViewController: UIViewController, CurrentIndexDelegate{
    var currentIndex: Int?
    func setCurrentIndex(index: Int?){
        currentIndex = index!
    }
    override func viewWillAppear(animated: Bool) {
        //Current index is set from delegate
        if(currentIndex != nil){
            collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: currentIndex!, inSection: 0), atScrollPosition: .Top, animated: true)
        }
    }

}

Upvotes: 0

André Slotta
André Slotta

Reputation: 14030

since you are not dismissing but popping the viewcontroller something like this should work:

override func viewWillDisappear(animated: Bool) {
    if let mainViewController = navigationController?.topViewController as? MainViewController {
        mainViewController.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: currentIndex, inSection: 0), atScrollPosition: .CenteredVertically, animated: false)
    }
    super.viewWillDisappear(animated)
}

Upvotes: 1

Arun Gupta
Arun Gupta

Reputation: 2636

When your currentViewController is dismissed, then ViewWillAppear of mainViewController will be called. Here you can implement the scrollToItemAtIndexPath with condition check that viewwillappear was called from currentVC was dismissed not when mainVC was launch from other sources.

Upvotes: 0

Related Questions