Swift 4:以编程方式切换页面视图控制器

时间:2018-02-14 17:31:54

标签: ios swift uipageviewcontroller

我需要使用按钮切换页面视图控制器。 initialViewController是CustomPageViewController。

我在View Controller中尝试了这个:

class MainViewController: UIViewController {

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

这在自定义类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)
}

但没有任何反应,任何想法? 感谢

编辑:最终的MainViewController代码正常工作

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

1 个答案:

答案 0 :(得分:1)

问题是这一行错了:

CustomPageViewController().goToProfile()

表达式CustomPageViewController()创建一个新的,独立的自定义页面视图控制器,它永远不会出现在界面中,并在下一行中被丢弃。

您需要的是引用到您界面中实际自定义页面视图控制器。

相关问题