这里以横向滑动为例,竖向同理,过程可以参考注释。
var dataList:[Any] = [] //数据源
var lastContentOffset: CGFloat = 0 //上次滑动的偏移量
var isDrag:Bool = false//是否处于滑动状态
//MARK: - UIScrollViewDelegate
extension ZJJTBaseVC: UIScrollViewDelegate {
//开始拖拽
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
//记录偏移量
lastContentOffset = scrollView.contentOffset.x
//业务逻辑
if dataList.count > 0 {
isDrag = true
}
}
//结束拖拽
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if decelerate == false {//没有减速
scrollViewHandleScrollWithScrollView(scrollView)
//业务逻辑
if dataList.count > 0 {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
self.isDrag = false
}
}
}
}
//开始减速
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
//开始减速(即手指离开屏幕)立即停止滚动
scrollView.setContentOffset(scrollView.contentOffset, animated: false)
scrollViewHandleScrollWithScrollView(scrollView)
//业务逻辑
if dataList.count > 0 {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
self.isDrag = false
}
}
}
//处理滑动到哪一个cell
func scrollViewHandleScrollWithScrollView(_ sender: UIScrollView) {
let offset = sender.contentOffset.x
if offset > lastContentOffset && offset - lastContentOffset > 30 {//右滑
if scrollIndex != dataList.count - 1 {
scrollIndex += 1
}
} else if offset < lastContentOffset && lastContentOffset - offset > 30 {//左滑
if scrollIndex != 0 {
scrollIndex -= 1
}
}
//业务逻辑
if collectionView != nil {
collectionView.scrollToItem(at: IndexPath.init(item: scrollIndex, section: 0), at: .centeredHorizontally, animated: true)
if scrollIndex == currentIndex {
let cell = self.collectionView.cellForItem(at: IndexPath.init(item: self.currentIndex, section: 0)) as? ZJJTBaseCollectionCell
if cell != nil {
cell!.isPlay = isPlay
}
}
}
}
}
网友评论