這里以橫向滑動(dòng)為例,豎向同理猜揪,過程可以參考注釋惭墓。
var dataList:[Any] = [] //數(shù)據(jù)源
var lastContentOffset: CGFloat = 0 //上次滑動(dòng)的偏移量
var isDrag:Bool = false//是否處于滑動(dòng)狀態(tài)
//MARK: - UIScrollViewDelegate
extension ZJJTBaseVC: UIScrollViewDelegate {
//開始拖拽
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
//記錄偏移量
lastContentOffset = scrollView.contentOffset.x
//業(yè)務(wù)邏輯
if dataList.count > 0 {
isDrag = true
}
}
//結(jié)束拖拽
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if decelerate == false {//沒有減速
scrollViewHandleScrollWithScrollView(scrollView)
//業(yè)務(wù)邏輯
if dataList.count > 0 {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
self.isDrag = false
}
}
}
}
//開始減速
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
//開始減速(即手指離開屏幕)立即停止?jié)L動(dòng)
scrollView.setContentOffset(scrollView.contentOffset, animated: false)
scrollViewHandleScrollWithScrollView(scrollView)
//業(yè)務(wù)邏輯
if dataList.count > 0 {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
self.isDrag = false
}
}
}
//處理滑動(dòng)到哪一個(gè)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
}
}
//業(yè)務(wù)邏輯
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
}
}
}
}
}