Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save christianselig/1555d08257133577e1fc929122e4c24f to your computer and use it in GitHub Desktop.
Save christianselig/1555d08257133577e1fc929122e4c24f to your computer and use it in GitHub Desktop.
import UIKit
import UIKit.UIGestureRecognizerSubclass
class ViewController: UIViewController {
let flickView = UIView()
var propertyAnimator: UIViewPropertyAnimator?
override func viewDidLoad() {
super.viewDidLoad()
flickView.backgroundColor = .systemOrange
flickView.frame = CGRect(x: 0.0, y: 0.0, width: 300.0, height: view.bounds.height)
view.addSubview(flickView)
let panGestureRecognizer = CustomPanGestureRecognizer(target: self, action: #selector(panned(panGestureRecognizer:)))
panGestureRecognizer.requiresExclusiveTouchType = true
flickView.addGestureRecognizer(panGestureRecognizer)
}
@objc private func panned(panGestureRecognizer: UIPanGestureRecognizer) {
if panGestureRecognizer.state == .began {
NSLog("Gesture began")
if let propertyAnimator {
let label = UILabel(frame: CGRect(x: 200.0, y: 100.0, width: 300.0, height: 300.0))
label.numberOfLines = 0
label.text = "Communicated"
view.addSubview(label)
propertyAnimator.stopAnimation(true)
self.propertyAnimator = nil
panGestureRecognizer.state = .cancelled
}
} else if panGestureRecognizer.state == .changed {
flickView.frame.origin.x = panGestureRecognizer.translation(in: flickView).x
} else if panGestureRecognizer.state == .ended {
NSLog("Gesture ended")
// Yes, a linear animation here is a horrible idea 😛
let propertyAnimator = UIViewPropertyAnimator(duration: 3.0, curve: .linear)
self.propertyAnimator = propertyAnimator
propertyAnimator.addAnimations {
self.flickView.frame.origin.x = self.view.bounds.width - self.flickView.bounds.width
}
propertyAnimator.startAnimation()
}
}
}
class CustomPanGestureRecognizer: UIPanGestureRecognizer {
var totalTouches = 0
let label = UILabel(frame: CGRect(x: 20.0, y: 100.0, width: 300.0, height: 300.0))
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesBegan(touches, with: event)
// Immediately change state to began, which should stop any existing animations
self.state = .began
totalTouches += 1
guard totalTouches > 1 else { return }
label.numberOfLines = 0
label.text = "Touched \(totalTouches)"
view!.superview!.addSubview(label)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment