问题
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