swift | 控制UIScrollView實現(xiàn)滑動分頁效果

這里以橫向滑動為例,豎向同理,過程可以參考注釋。

var dataList:[Any] = [] //數(shù)據(jù)源
var lastContentOffset: CGFloat = 0 //上次滑動的偏移量
var isDrag:Bool = false//是否處于滑動狀態(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動
        scrollView.setContentOffset(scrollView.contentOffset, animated: false)
        scrollViewHandleScrollWithScrollView(scrollView)
        //業(yè)務(wù)邏輯
        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
            }
        }

        //業(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
                }
            }
        }
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容