我正在尝试实现滚动视图,在滚动时捕捉到点。
此处的所有帖子我都看到过关于“'用户已经结束拖动滚动。我想在拖动过程中使它快速捕捉。
到目前为止,我有这个在拖动后停止惯性并且工作正常:
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
targetContentOffset.memory = scrollView.contentOffset
}
我尝试了这个但没有按照预期工作:
var scrollSnapHeight : CGFloat = myScrollView.contentSize.height/10
scrollViewDidScroll:
func scrollViewDidScroll(scrollView: UIScrollView) {
let remainder : CGFloat = scrollView.contentOffset.y % scrollSnapHeight
var scrollPoint : CGPoint = scrollView.contentOffset
if remainder != 0 && scrollView.dragging
{
if self.lastOffset > scrollView.contentOffset.y //Scrolling Down
{
scrollPoint.y += (scrollSnapHeight - remainder)
NSLog("scrollDown")
}
else //Scrolling Up
{
scrollPoint.y -= (scrollSnapHeight - remainder)
}
scrollView .setContentOffset(scrollPoint, animated: true)
}
self.lastOffset = scrollView.contentOffset.y;
}
答案 0 :(得分:6)
此方法将启用/禁用scrollEnabled
的{{1}}属性。
当scrollView滚动到给定UIScrollView
之外时,将scrollSnapHeight
设为scrollEnabled
。这将停止滚动。然后再次启用滚动以进行下一次拖动。
false
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView.contentOffset.y > lastOffset + scrollSnapHeight {
scrollView.scrollEnabled = false
} else if scrollView.contentOffset.y < lastOffset - scrollSnapHeight {
scrollView.scrollEnabled = false
}
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
guard !decelerate else {
return
}
setContentOffset(scrollView)
}
func scrollViewWillBeginDecelerating(scrollView: UIScrollView) {
setContentOffset(scrollView)
}
}
答案 1 :(得分:3)
此解决方案不需要您抬起手指以便在滚动时解除锁定和工作。如果您需要垂直滚动而不是水平滚动,只需将x与y交换。
将 snapPoint 设置为您希望捕捉中心所在的内容偏移量。
将 snapOffset 设置为snapPoint周围所需的半径,以便进行捕捉。
如果您需要知道scrollView是否已快照,只需检查 isSnapped 变量。
class UIScrollViewSnapping : UIScrollView {
public var snapPoint: CGPoint?
public var snapOffset: CGFloat?
public var isSnapped = false
public override var contentOffset: CGPoint {
set {
if let snapPoint = self.snapPoint,
let snapOffset = self.snapOffset,
newValue.x > snapPoint.x - snapOffset,
newValue.x < snapPoint.x + snapOffset {
self.isSnapped = true
super.contentOffset = snapPoint
}
else {
self.isSnapped = false
super.contentOffset = newValue
}
}
get {
return super.contentOffset
}
}
}