执行按钮操作后的UICollectionView scrollToItemAtIndex

时间:2016-03-20 19:54:37

标签: ios swift

当弹出currentViewController时,我想将UICollectionView中的mainViewController滚动到currentViewController当前所在项目的索引处。我已尝试在currentViewController的viewWillDisappear中实现此功能,但执行back button操作时没有任何操作。

   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)
        }
    }

3 个答案:

答案 0 :(得分:1)

因为你不是解雇而是弹出,所以这样的viewcontroller应该有效:

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)
}

答案 1 :(得分:0)

当你的currentViewController被解散时,将调用mainViewController的ViewWillAppear。在这里你可以实现scrollToItemAtIndexPath,条件检查是从currentVC调用viewwillappear被取消,而不是从其他来源启动mainVC时。

答案 2 :(得分:0)

结束创建了一个更易于管理的协议,可以写入childVC viewWillDisappear中的所有内容。感谢您André Slotta提出的建议。

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)
        }
    }

}