2017-06-16 25 views
0

我有以下的功能,我想只要用戶從一個頁面揮筆到另一個(垂直分頁)打電話:檢測變化頁動畫的完成到另一個頁面中UIPageViewController

func sendNotification(){ 

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "stopVideo"), object: nil) 
    print("called") 

} 

目前,只要pageAfter或-before被創建,就會調用該函數。使用該功能「創造」了下一頁/上一頁看起來像這樣(在這種情況下,它是viewControllerAfter):

func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { 

    let currentIndexString = (viewController as! MyViewController).index 
    let currentIndex  = indec.index(of: currentIndexString!) 

    //set if so that next page 
    if currentIndex! < indec.count - 1 { 

     let myViewController = MyViewController() 

     myViewController.index   = indec[currentIndex! + 1] 

     sendNotification() //function is called 

     return myViewController 

    } 

    return nil 

} 

由於UIPageViewController有所準備以下頁面,並回到前一個頁面也不會調用該函數(因爲視圖控制器不需要被「創建」)我沒有得到我想要的結果。我想知道是否有一個功能,我可以在完成動畫時調用sendNotification()。我發現很多關於跳到另一頁的問題,但沒有涉及我的問題。我真的很感謝你的幫助!

回答

3

可以使用UIPageViewControllerDelegate功能

func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) 
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) 

隨着這些功能的名字說,當用戶滑動到PageViewController的另一個頁面時,第一個會被調用。

第二個將被調用,當過渡已經完成,這意味着用戶的動畫之後看到的下一個頁面。

在這兩個你都可以檢查頁面之間的變化。

也不要忘記檢查第二函數的completed變量。如果用戶開始滑動然後不進入下一頁(因爲他在它之前釋放手指或類似),它是錯誤的,並且您沒有新的ViewController。

陣列previousViewControllers保持最近顯示控制器,其中previousViewControllers[0]可能是之前所示。

欲瞭解更多信息中查找documentation

+0

我仍然在學習迅速而不能完全肯定我怎麼會叫我的函數裏......我加入到'UIPageViewControllerDelegate'上我的課的類型,並試圖簡單地把我的功能裏面的第二個功能,但它不工作... – Moritz

+0

你可以更新你的問題,並顯示使用委託方法? –

+0

發現我的錯誤,忘了'delegate = self' ...♂️謝謝! – Moritz

1

也許這將有利於你在UIPageViewControllerDelegate方法的文檔documentation運行您的通知方法:

optional func pageViewController(_ pageViewController: UIPageViewController, 
       didFinishAnimating finished: Bool, 
     previousViewControllers: [UIViewController], 
      transitionCompleted completed: Bool) 
相關問題