Created
January 23, 2017 23:57
-
-
Save spacedrabbit/60821d6d19b216f87e7143a54153b35e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import SnapKit | |
// Stage 4 ensures that only tapping inside of the bounds of the view will cause the animations to happen | |
class TouchAnimatorViewController: UIViewController { | |
var animator: UIViewPropertyAnimator? = nil | |
let squareSize = CGSize(width: 100.0, height: 100.0) | |
var viewIsCurrentlyHeld: Bool = false | |
// MARK: - View LifeCycle | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
setupViewHierarchy() | |
configureConstraints() | |
} | |
// MARK: - Setup | |
private func configureConstraints() { | |
darkBlueView.snp.makeConstraints{ view in | |
view.center.equalToSuperview() | |
view.size.equalTo(squareSize) | |
} | |
} | |
private func setupViewHierarchy() { | |
self.view.backgroundColor = .white | |
self.view.isUserInteractionEnabled = true | |
view.addSubview(darkBlueView) | |
} | |
// MARK: - Movement | |
internal func move(view: UIView, to point: CGPoint) { | |
if animator!.isRunning { | |
animator?.addAnimations { | |
self.view.layoutIfNeeded() | |
} | |
} | |
view.snp.remakeConstraints { (view) in | |
view.center.equalTo(point) | |
view.size.equalTo(squareSize) | |
} | |
} | |
internal func pickUp(view: UIView) { | |
animator = UIViewPropertyAnimator(duration: 0.2, curve: .easeOut, animations: { | |
view.transform = CGAffineTransform(scaleX: 1.2, y: 1.2) | |
}) | |
animator?.startAnimation() | |
} | |
internal func putDown(view: UIView) { | |
animator = UIViewPropertyAnimator(duration: 0.15, curve: .easeIn, animations: { | |
view.transform = CGAffineTransform.identity | |
}) | |
animator?.startAnimation() | |
} | |
// MARK: - Tracking Touches | |
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { | |
guard let touch = touches.first else { return } | |
let touchWasInsideOfDarkBlueView = darkBlueView.frame.contains(touch.location(in: view)) | |
if touchWasInsideOfDarkBlueView { | |
pickUp(view: darkBlueView) | |
} | |
} | |
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { | |
putDown(view: darkBlueView) | |
} | |
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { | |
guard let touch = touches.first else { return } | |
move(view: darkBlueView, to: touch.location(in: view)) | |
} | |
// MARK: - Views | |
internal lazy var darkBlueView: UIView = { | |
let view: UIView = UIView() | |
view.backgroundColor = Colors.darkBlue | |
return view | |
}() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment