Skip to content

Instantly share code, notes, and snippets.

@kboy-silvergym
Last active November 14, 2019 15:18
Show Gist options
  • Save kboy-silvergym/8103785e210486bc4485b72409373561 to your computer and use it in GitHub Desktop.
Save kboy-silvergym/8103785e210486bc4485b72409373561 to your computer and use it in GitHub Desktop.
Snapchat like PageViewController which is changing its alpha of background color as scrolling.
import UIKit
enum TutorialNumber {
case first
case second
}
protocol TutorialVC: class {
var number: TutorialNumber { get set }
}
class PageViewController: UIPageViewController {
lazy var tutorial1: UIViewController = {
let storyboard = UIStoryboard(name: "Tutorial1", bundle: nil)
let vc = storyboard.instantiateInitialViewController()!
if let tutorialVC = vc as? TutorialVC {
tutorialVC.number = .first
}
return vc
}()
lazy var tutorial2: UIViewController = {
let storyboard = UIStoryboard(name: "Tutorial2", bundle: nil)
let vc = storyboard.instantiateInitialViewController()!
if let tutorialVC = vc as? TutorialVC {
tutorialVC.number = .second
}
return vc
}()
var currentNumber: TutorialNumber = .first
private lazy var screenWidth = UIScreen.main.bounds.width
override func viewDidLoad() {
super.viewDidLoad()
self.setViewControllers([tutorial1], direction: .forward, animated: true, completion: nil)
self.dataSource = self
self.view.backgroundColor = .clear
for subView in self.view.subviews {
if let scrollView = subView as? UIScrollView {
scrollView.delegate = self
}
}
}
}
extension PageViewController: UIPageViewControllerDataSource {
// swipe to go left
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let vc = viewController as? TutorialVC else {
return nil
}
switch vc.number {
case .first:
return nil
case .second:
return tutorial1
}
}
// swipe to go right
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let vc = viewController as? TutorialVC else {
return nil
}
switch vc.number {
case .first:
return tutorial2
case .second:
return nil
}
}
}
extension PageViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.x
let alpha = (offset - screenWidth) / screenWidth
switch currentNumber {
case .first:
self.view.backgroundColor = UIColor.yellow.withAlphaComponent(alpha)
case .second:
let reverseAlpha = 1.0 + alpha
self.view.backgroundColor = UIColor.yellow.withAlphaComponent(reverseAlpha)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment