Swift 4 : Switch Page View Controller programatically [duplicate]

跟風遠走 提交于 2019-12-25 18:29:12

问题


I need to switch Page View Controller using a button. The initialViewController is the CustomPageViewController.

I tried this in the View Controller :

class MainViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
}    
@IBAction func goProfile(_ sender: Any) {
    CustomPageViewController().goToProfile()
}

And this in the custom class PageViewController :

class CustomPageViewController: UIPageViewController {

fileprivate lazy var pages: [UIViewController] = {
    return [
        self.getViewController(withIdentifier: "MainViewController"),
        self.getViewController(withIdentifier: "ProfilViewController")
    ]
}()

fileprivate func getViewController(withIdentifier identifier: String) -> UIViewController
{
    return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: identifier)
}

override func viewDidLoad()
{
    super.viewDidLoad()
    self.dataSource = self
    self.delegate   = self

    if let firstVC = pages.first
    {
        setViewControllers([firstVC], direction: .forward, animated: true, completion: nil)
    }
}

func goToProfile(){
    setViewControllers([pages.last!], direction: .forward, animated: true, completion: nil)
}

But nothing happens, any ideas ? Thanks

EDIT : Final MainViewController's code working

@IBAction func goProfile(_ sender: Any) {
    let vc = UIApplication.shared.keyWindow?.rootViewController as! CustomPageViewController
    vc.goToProfile()
}

回答1:


The problem is that this line is wrong:

CustomPageViewController().goToProfile()

The expression CustomPageViewController() creates a new, separate custom page view controller, which never appears in the interface and is thrown away in the next line.

What you need is a reference to an actual custom page view controller that is in your interface.



来源:https://stackoverflow.com/questions/48793064/swift-4-switch-page-view-controller-programatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!