Interpolateというライブラリを試してみました。
まずはCocoaPodsでインストールします。
target 'MyApp' do use_frameworks! pod 'Interpolate' end
次に実際に実装してみます。
今回は画面をスワイプすると色が黒から白に変わるというものを作ってみようと思います。
まずは下のようにInterpolateをwhiteとblackを渡して初期化します。
import UIKit import Interpolate class ViewController: UIViewController { var interpolate: Interpolate? override func viewDidLoad() { super.viewDidLoad() interpolate = Interpolate(from: UIColor.white, to: UIColor.black, apply: { [weak self] color in self?.view.backgroundColor = color }) } }
Interpolateは、下のようにprogressをセットして使います。
下のように0.5を入れれば、applyに灰色(初期化時に渡したfromとtoの中間色)を引数に呼び出されます。
progressに1.0を入れればtoの黒色が引数に渡され、0.0の場合はfromの白色が渡されます。
interpolate = Interpolate(from: UIColor.white, to: UIColor.black, apply: { [weak self] color in self?.view.backgroundColor = color }) interpolate?.progress = 0.5
次はスワイプに応じてprogressを渡す処理を実装します。
下のようにUIPanGestureRecognizerをセットします。
class ViewController: UIViewController { var interpolate: Interpolate? override func viewDidLoad() { super.viewDidLoad() interpolate = Interpolate(from: UIColor.white, to: UIColor.black, apply: { [weak self] color in self?.view.backgroundColor = color }) view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(self.swipeView(sender:)))) } @objc func swipeView(sender: UIPanGestureRecognizer) { let translation = sender.translation(in: view) let translatedCenterX = view.center.x + translation.x let progress = translatedCenterX / view.bounds.size.width interpolate?.progress = progress } }
これでスワイプに応じて白から黒に変わる処理が実装できました。
Interpolateですが、色だけでなくCGPointやCGFloatなども渡す事ができます。
Interpolate(from: CGPoint(x: 0, y: 0), to: CGPoint(x: 100, y: 100), apply: { [weak self] point in })