我试图模仿 iOS 照片应用程序。这是我的逻辑:
// CALCULATE A CONTENT OFFSET FOR SNAPPING POINT
let snapPoint = CGPoint(x: 367, y: 0)
// CHANGE THESE VALUES TO TEST
let minDistanceToSnap = 7.0
let minVelocityToSnap = 25.0
let minDragDistanceToReleaseSnap = 7.0
let snapDuringDecelerating = false
这种滚动需要3个阶段
enum SnapState {
case willSnap
case didSnap
case willRelease
}
willSnap:
默认状态。决定何时拍摄。比较contentOffset distance from SnapPoint with minDistanceToSnap
和scrollview velocity with minVelocityToSnap
。改变didSnap
状态。
didSnap:
手动setContentOffset
到提供的contextOffset(snapPoint)
. dragDistance
上计算scrollView
。如果用户拖动超过一定距离 ( minDragDistanceToReleaseSnap
) 更改为willRelease
状态。
willRelease:
如果大于则再次更改willSnap
状态。distance scroll from snapPoint
minDistanceToSnap
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
switch(snapState) {
case .willSnap:
let distanceFromSnapPoint = distance(between: scrollView.contentOffset, and: snapPoint)
let velocity = scrollView.panGestureRecognizer.velocityInView(view)
let velocityDistance = distance(between: velocity, and: CGPointZero)
if distanceFromSnapPoint <= minDistanceToSnap && velocityDistance <= minVelocityToSnap && (snapDuringDecelerating || velocityDistance > 0.0) {
startSnapLocaion = scrollView.panGestureRecognizer.locationInView(scrollView)
snapState = .didSnap
}
case .didSnap:
scrollView.setContentOffset(snapPoint, animated: false)
var dragDistance = 0.0
let location = scrollView.panGestureRecognizer.locationInView(scrollView)
dragDistance = distance(between: location, and: startSnapLocaion)
if dragDistance > minDragDistanceToReleaseSnap {
startSnapLocaion = CGPointZero
snapState = .willRelease
}
case .willRelease:
let distanceFromSnapPoint = distance(between: scrollView.contentOffset, and: snapPoint)
if distanceFromSnapPoint > minDistanceToSnap {
snapState = .willSnap
}
}
}
}
辅助函数
func distance(between point1: CGPoint, and point2: CGPoint) -> Double {
return Double(hypotf(Float(point1.x - point2.x), Float(point1.y - point2.y)))
}
在 Github 上做了一个演示项目:https ://github.com/rishi420/SnapDrag
注意:使用 Xcode 7.2 制作的项目。您可能需要进行一些更改才能编译。