LoginSignup
0

More than 5 years have passed since last update.

スクロールに合わせて背景色がじわじわ切り替わるPageViewControllerの実装

Last updated at Posted at 2018-11-07

GIF image-41F1D5F44551-1.gif

Snapchatっぽく、PageViewControllerに合わせて背景のalphaが変わるやつをやってみました。
ちなみに後ろにCameraのViewControllerを表示してその上にPageViewControllerを置いています。

①PageVCをUIScrollViewDelegateに準拠させる

    override func viewDidLoad() {
        super.viewDidLoad()

        for subView in self.view.subviews {
            if let scrollView = subView as? UIScrollView {
                scrollView.delegate = self
            }
        }
    }

②UIScrollViewDelegateでスクロール位置を把握し、alphaを変化させる

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

全体のコードはこちら

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0