Swift 4:以编程方式切换页面视图控制器 [英] Swift 4 : Switch Page View Controller programatically

查看:36
本文介绍了Swift 4:以编程方式切换页面视图控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这在自定义类 PageViewController 中:

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

最终 MainViewController 的代码工作

EDIT : Final MainViewController's code working

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

推荐答案

问题是这行不对:

CustomPageViewController().goToProfile()

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

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.

这篇关于Swift 4:以编程方式切换页面视图控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆