Created
December 2, 2016 02:49
-
-
Save AntonTheDev/192ec21665e5679886d202637d9b3e34 to your computer and use it in GitHub Desktop.
Scroll Direction Locking CollectionView, Relative to UICollectionViewFlowLayout (Proof of Concept)
This file contains hidden or 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 Foundation | |
import UIKit | |
class UIDirectionAbidingCollectionView : UICollectionView { | |
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { | |
super.init(frame: frame, collectionViewLayout: layout) | |
setupDelayRecognizer() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
setupDelayRecognizer() | |
} | |
func setupDelayRecognizer() { | |
addGestureRecognizer(delayPanGestureRecognizer) | |
panGestureRecognizer.delaysTouchesBegan = true | |
} | |
lazy var delayPanGestureRecognizer: UIPanGestureRecognizer = { | |
var recognizer = UIPanGestureRecognizer() | |
recognizer.delegate = self | |
return recognizer | |
}() | |
} | |
extension UIDirectionAbidingCollectionView: UIGestureRecognizerDelegate { | |
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { | |
return true | |
} | |
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { | |
if (gestureRecognizer == delayPanGestureRecognizer && otherGestureRecognizer == panGestureRecognizer) { | |
return true | |
} | |
return false | |
} | |
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { | |
if gestureRecognizer == delayPanGestureRecognizer { | |
if let flowLayout = self.collectionViewLayout as? UICollectionViewFlowLayout { | |
let scrollDirection = flowLayout.scrollDirection | |
let translation = delayPanGestureRecognizer.translation(in: self) | |
let xTransaltionValue = (translation.x * translation.x) | |
let yTransaltionValue = (translation.y * translation.y) | |
if scrollDirection == .vertical && xTransaltionValue > yTransaltionValue { | |
return true | |
} | |
else if scrollDirection == .horizontal && xTransaltionValue < yTransaltionValue { | |
return true | |
} | |
else { | |
return false | |
} | |
} | |
} | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment