Swift:如何以编程方式推进容器视图内的UIPageViewController?

时间:2019-03-16 15:50:45

标签: ios swift uipageviewcontroller uicontainerview

我有一个ViewController,其中包含一个按钮和两个我想永久保留的图像视图,以及一个可以在其他三个ViewController中滑动的PageViewController,它们都能很好地工作,但是我不知道该怎么做按下按钮时,如何以编程方式转到下一张幻灯片。

这是我的PageController类的样子(基于Fattie在这里非常有用的答案:UIPageViewController and storyboard):

class PageController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {


var pages = [UIViewController]()

override func viewDidLoad() {
    super.viewDidLoad()

    self.delegate = self
    self.dataSource = self

    let p1: UIViewController! = storyboard?.instantiateViewController(withIdentifier: "onboardingText01")
    let p2: UIViewController! = storyboard?.instantiateViewController(withIdentifier: "onboardingText02")
    let p3: UIViewController! = storyboard?.instantiateViewController(withIdentifier: "onboardingText03")

    pages.append(p1)
    pages.append(p2)
    pages.append(p3)

    setViewControllers([p1], direction: UIPageViewController.NavigationDirection.forward, animated: false, completion: nil)

}


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

    let currentPage = pages.index(of: viewController)!

    // used to prevent the PageViewController from looping
    if currentPage == 0 { return nil }

    let prev = abs((currentPage - 1) % pages.count)
    return pages[prev]

}

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

    let currentPage = pages.index(of: viewController)!

    // used to prevent the PageViewController from looping
    if currentPage == (pages.count - 1) { return nil }

    let nxt = abs((currentPage + 1) % pages.count)
    return pages[nxt]
}

func presentationIndex(for pageViewController: UIPageViewController)-> Int {
    return pages.count
}

}

然后将按钮定义为ViewController中包含所有这些内容(单独文件)的动作。

我尝试使用通知/观察者,但出现错误

  

类型'UIPageViewController'没有成员'advancePage'

使用选择器(我不确定如何调用该函数)。

内部viewDidLoad:

NotificationCenter.default.addObserver(self, selector: #selector(UIPageViewController.advancePage()), name: advance, object: nil)

在UIPageViewController类内部

    func advancePage(){
        setViewControllers(pages,
                           direction: UIPageViewController.NavigationDirection.forward,
                           animated: true,
                           completion: nil)
    }

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您需要将其添加到PageController的{​​{1}}

viewDidLoad

NotificationCenter.default.addObserver(self, selector: #selector(self.advancePage), name: advance, object: nil)