我知道有些人以前提过这个问题,但他们都是关于UITableViews或UIScrollViews的,我无法得到我所接受的解决方案.我想要的是在水平滚动我的UICollectionView时的捕捉效果 – 很像iOS AppStore中发生的情况. iOS 9是我的目标版本,所以请在回答之前先看看UIKit的更改.
谢谢.
解决方法
这是值得的,这是一个简单的计算,我用(
swift):
func snapToNearestCell(scrollView: UIScrollView) {
//pick first cell to get width
let indexPath = NSIndexPath(forItem: 0,inSection: 0)
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as UICollectionViewCell? {
let cellWidth = cell.bounds.size.width
for i in 0..<collectionView.numberOfItemsInSection(0) {
if scrollView.contentOffset.x <= CGFloat(i) * cellWidth + cellWidth / 2 {
let indexPath = NSIndexPath(forItem: i,inSection: 0)
collectionView.scrollToItemAtIndexPath(indexPath,atScrollPosition: .CenteredHorizontally,animated: true)
break
}
}
}
}
呼叫你需要的地方我叫它
func scrollViewDidEndDragging(scrollView: UIScrollView,willDecelerate decelerate: Bool) {
snapToNearestCell(scrollView)
}
和
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
snapToNearestCell(scrollView)
}