How to make a UIScrollView snap to icons (like App Store: Feature)

后端 未结 4 1676
渐次进展
渐次进展 2020-12-24 10:14

What I want to get is the same behaviour that this scroll view has:

\"App

4条回答
  •  -上瘾入骨i
    2020-12-24 10:40

    Chiming in for Swift. @avdyushin's answer is by far the simplest and, as Ben mentioned, works very well. Although I did add a piece from @Rob's answer regarding the end of the scrollview. Together, this solution seems to work perfectly.

    func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) {
    
        if ((scrollView.contentOffset.x + scrollView.frame.size.width) >= scrollView.contentSize.width) {
            // no snap needed ... we're at the end of the scrollview
            return
        }
    
        let index: CGFloat = CGFloat(lrintf(Float(targetContentOffset.memory.x) / kCellBaseWidth))
        targetContentOffset.memory.x = index * kCellBaseWidth
    
    }
    

    Just add your minimumLineSpacing to kCellBaseWidth, and voila.

提交回复
热议问题