自定义ScrollView滚动整数单元格距离/居中显示
2018-11-14 本文已影响0人
MEKevin
方法一:
方法一效果
//滚动自然
//注意:isPagingEnabled = fasle
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let targetOffset: CGPoint = getNearestContentOffset(targetContentOffset.pointee)
print(self.bannerCollectView.contentOffset.x)
targetContentOffset.pointee = targetOffset
}
func getNearestContentOffset(_ offset: CGPoint) -> CGPoint {
let pageSize = itemWidth + miniSpace
let newPage: Int = Int(roundf(Float(offset.x/pageSize)))
return CGPoint(x: CGFloat(newPage) * pageSize, y: offset.y)
}
方法二:
方法二效果
//注意:isPagingEnabled = true
//每次只滚动一个单元格距离
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
stopOffsetX = scrollView.contentOffset.x
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
//如果是向右滑或者滑动距离大于item的一半,则像右移动一个item+space的距离,反之向左
let currentPointX = scrollView.contentOffset.x
let moveLen: CGFloat = currentPointX - stopOffsetX
let shouldPage: Int = Int(moveLen/(itemWidth/2 + miniSpace/2)) //一次只能滚动一格
if velocity.x > 0 || shouldPage > 0 {
dragLen = 1
} else if velocity.x < 0 || shouldPage < 0 {
dragLen = -1
} else {
dragLen = 0
}
}
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
let currentndIndex: UInt = UInt(stopOffsetX + CGFloat(itemWidth + miniSpace)*0.5) / UInt(itemWidth + miniSpace)
bannerCollectView.scrollToItem(at: NSIndexPath.init(row: Int(currentndIndex) + dragLen, section: 0) as IndexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: true)
}