Skip to content

[Feature]: Snap the card view to top or bottom automatically #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion CardViewAnimation/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ class ViewController: UIViewController {
return cardVisible ? .collapsed : .expanded
}

var velocityFactor : CGFloat = 1000

var runningAnimations = [UIViewPropertyAnimator]()
var animationProgressWhenInterrupted:CGFloat = 0

Expand Down Expand Up @@ -78,7 +80,29 @@ class ViewController: UIViewController {
fractionComplete = cardVisible ? fractionComplete : -fractionComplete
updateInteractiveTransition(fractionCompleted: fractionComplete)
case .ended:
continueInteractiveTransition()
//Here, check where to snap the card view as velocity and position
//of card view (while drag) changes.
//velocityFactor decides how much velocity contributes in the
//decision of where to snap the card view.
let translation = recognizer.translation(in: self.cardViewController.handleArea)
var fractionCompleted = translation.y/cardHeight
var velocity = recognizer.velocity(in: self.cardViewController.handleArea).y
velocity = velocity > 0 ? velocity : -velocity
fractionCompleted = fractionCompleted > 0 ? fractionCompleted : -fractionCompleted
let modifiedFraction = velocity/velocityFactor + fractionCompleted
if modifiedFraction >= 0.5 {
//Just go with the flow
continueInteractiveTransition()
} else {
//Reverse animation direction
for animator in runningAnimations {
animator.isReversed = true
}
//Change card state to cancel out the one in the completion block.
cardVisible = !cardVisible
continueInteractiveTransition()
}

default:
break
}
Expand Down