Swift PageViewController内からページングを行うサンプル

やること

PageViewController内のボタンからページングを行う

実行結果


PageViewController on Swift

スマニュー的なUIの実装の方が楽に遷移できそうなきがする.

コード

ViewController.swift

import UIKit

class ViewController: UIViewController {
    var way:UIPageViewControllerNavigationDirection = .forward
    var at = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let r: CGFloat = CGFloat(arc4random_uniform(255)+1) / 255.0
        let g: CGFloat = CGFloat(arc4random_uniform(255)+1) / 255.0
        let b: CGFloat = CGFloat(arc4random_uniform(255)+1) / 255.0
        let color: UIColor = UIColor(red: r, green: g, blue: b, alpha: 1.0)
        view.backgroundColor = color
        let button = UIButton()
        button.setTitle("Tap Me!", for: .normal)
        button.setTitleColor(UIColor.blue, for: .normal)
        button.setTitle("Tapped!", for: .highlighted)
        button.setTitleColor(UIColor.red, for: .highlighted)
        button.frame = CGRect(x: 0,y: 0,width: 300,height: 50)
        button.tag = 1
        button.layer.position = CGPoint(x: self.view.frame.width / 2, y: view.bounds.height / 2)
        button.backgroundColor = UIColor.white
        button.layer.cornerRadius = 10
        button.layer.borderWidth = 1
        button.addTarget(self, action: #selector(self.buttonTapped), for:.touchDown)
        view.addSubview(button)
    }

    @objc func buttonTapped() {
        if let vc = self.parent as? PageViewController {
            vc.setViewControllers([vc.vcArray[at]], direction: way, animated: true, completion: nil)
        }
    }
}

PageViewController.swift

import UIKit

class PageViewController: UIPageViewController, UIPageViewControllerDataSource {
    var vcArray:[UIViewController] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.dataSource = self
        let vc1 = ViewController()
        vc1.way = .forward
        vc1.at = 1
        vcArray.append(vc1)
        let vc2 = ViewController()
        vc2.way = .reverse
        vc2.at = 0
        vcArray.append(vc2)
        self.setViewControllers([vcArray[0]], direction: .reverse, animated: true, completion: nil)
        self.view.backgroundColor = UIColor.white
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        guard let index = vcArray.index(of: viewController), index > 0 else {
            return nil
        }
        
        return vcArray[index - 1]
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?
    {
        guard let index = vcArray.index(of: viewController), index < vcArray.count - 1 else {
            return nil
        }
        
        return vcArray[index + 1]
    }
}