Swift - UICollectionView 長(zhǎng)按拖拽

導(dǎo)讀

簡(jiǎn)單用Swift寫(xiě)了一個(gè)collectionview的拖拽點(diǎn)擊排序效果;
拖拽排序是新聞?lì)惖腁pp可以說(shuō)是必有的交互設(shè)計(jì),如今日頭條,網(wǎng)易新聞等。

效果

效果

主要代碼

手勢(shì)長(zhǎng)按移動(dòng)

  • 1.給CollectionViewCell添加一個(gè)長(zhǎng)按手勢(shì).

private lazy var collectionView: UICollectionView = {

        let clv = UICollectionView(frame: self.view.frame, collectionViewLayout: ChannelViewLayout())
        clv.backgroundColor = UIColor.white
        clv.delegate = self
        clv.dataSource = self
        clv.register(ChannelViewCell.self, forCellWithReuseIdentifier: ChannelViewCellIdentifier)
        clv.register(ChannelHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: ChannelViewHeaderIdentifier)
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPressGesture(_:)))
        clv.addGestureRecognizer(longPress)
        
        return clv
    }()
  • 2.開(kāi)始長(zhǎng)按時(shí)對(duì)cell進(jìn)行截圖或拷貝一個(gè)cell,并隱藏cell.
    //MARK: - 長(zhǎng)按開(kāi)始
    private func dragBegan(point: CGPoint) {
        
        indexPath = collectionView.indexPathForItem(at: point)
        if indexPath == nil || (indexPath?.section)! > 0 || indexPath?.item == 0
        {return}
        
        let item = collectionView.cellForItem(at: indexPath!) as? ChannelViewCell
        item?.isHidden = true
        dragingItem.isHidden = false
        dragingItem.frame = (item?.frame)!
        dragingItem.text = item!.text
        //放大效果(此處可以根據(jù)需求隨意修改)
        dragingItem.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
        
    }

  • 3.在手勢(shì)移動(dòng)的時(shí)候,找到目標(biāo)是的indexPatch,再調(diào)用系統(tǒng)的api交換這個(gè)cell和隱藏cell的位置,并且更新數(shù)據(jù).
    //MARK: - 移動(dòng)過(guò)程
    private func drageChanged(point: CGPoint) {

        if indexPath == nil || (indexPath?.section)! > 0 || indexPath?.item == 0 {return}
        dragingItem.center = point
        targetIndexPath = collectionView.indexPathForItem(at: point)
        if targetIndexPath == nil || (targetIndexPath?.section)! > 0 || indexPath == targetIndexPath || targetIndexPath?.item == 0 {return}
        // 更新數(shù)據(jù)
        let obj = selectedArr[indexPath!.item]
        selectedArr.remove(at: indexPath!.row)
        selectedArr.insert(obj, at: targetIndexPath!.item)
        //交換位置
        collectionView.moveItem(at: indexPath!, to: targetIndexPath!)
        //進(jìn)行記錄
        indexPath = targetIndexPath

    }

  • 4.手勢(shì)停止或取消時(shí),移除view,顯示隱藏cell. (這里手勢(shì)取消也要掉用此方法)
//MARK: - 長(zhǎng)按結(jié)束或取消
    private func drageEnded(point: CGPoint) {
        
        if indexPath == nil || (indexPath?.section)! > 0 || indexPath?.item == 0 {return}
        let endCell = collectionView.cellForItem(at: indexPath!)
        
        UIView.animate(withDuration: 0.25, animations: {
        
            self.dragingItem.transform = CGAffineTransform.identity
            self.dragingItem.center = (endCell?.center)!
            
        }, completion: {
        
            (finish) -> () in
            
            endCell?.isHidden = false
            self.dragingItem.isHidden = true
            self.indexPath = nil
            
        })
        
    }

點(diǎn)擊移動(dòng)

  • collectionView的點(diǎn)擊方法,我這里分為兩段,第一段為點(diǎn)擊處理事件,第二段為點(diǎn)擊添加添加標(biāo)簽(編輯狀態(tài)下第一段可以點(diǎn)擊排序)
   func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        
        if indexPath.section > 0 {
            
            // 更新數(shù)據(jù)
            let obj = recommendArr[indexPath.item]
            recommendArr.remove(at: indexPath.item)
            selectedArr.append(obj)
            //移動(dòng)方法
            collectionView.moveItem(at: indexPath, to: NSIndexPath(item: selectedArr.count - 1, section: 0) as IndexPath)
            
        } else {
            
            if isEdite {
                
                if indexPath.item == 0 {return}
                // 更新數(shù)據(jù)
                let obj = selectedArr[indexPath.item]
                selectedArr.remove(at: indexPath.item)
                recommendArr.insert(obj, at: 0)
                //移動(dòng)方法
                collectionView.moveItem(at: indexPath, to: NSIndexPath(item: 0, section: 1) as IndexPath)
                
            } else {
                
                if switchoverCallback != nil {
                    //處理點(diǎn)擊的閉包
                    switchoverCallback!(selectedArr, recommendArr, indexPath.item)
                    _ = navigationController?.popViewController(animated: true)
                }
            }
        }
        
        
        
    }

其他

此代碼只是一個(gè)效果,沒(méi)有怎么封裝,如果仔細(xì)看過(guò)的朋友可以知道其實(shí)沒(méi)有多么復(fù)雜

  • 點(diǎn)擊移動(dòng)
collectionView.moveItem(at: indexPath, to: NSIndexPath(item: 0, section: 1) as IndexPath)
  • 拖拽移動(dòng)
collectionView.moveItem(at: indexPath!, to: targetIndexPath!)

主要就是這兩個(gè)方法,其他都是處理邏輯以及視圖效果.

提示

如果你們是從iOS9開(kāi)始適配的話,那么可以用系統(tǒng)的Api,非常簡(jiǎn)單好用,大家這里可以自己去試試.

    // Support for reordering
    @available(iOS 9.0, *)
    open func beginInteractiveMovementForItem(at indexPath: IndexPath) -> Bool // returns NO if reordering was prevented from beginning - otherwise YES

    @available(iOS 9.0, *)
    open func updateInteractiveMovementTargetPosition(_ targetPosition: CGPoint)

    @available(iOS 9.0, *)
    open func endInteractiveMovement()

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

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

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,635評(píng)論 4 61
  • 2016年除夕夜,我一個(gè)人圍著毯子煮泡面,吃干了的甜味爆米花,選一部自認(rèn)為好哭好笑的電影度過(guò)這個(gè)夜晚。 12點(diǎn)一到...
    ZOOKEE閱讀 631評(píng)論 6 4
  • 回家,回家過(guò)年是每個(gè)在外地工作的游子每年的必修課。過(guò)程伴隨著期盼和艱辛。 對(duì)一年回家一次的游子來(lái)說(shuō)春節(jié)一定要回家過(guò)...
    逸云亦水閱讀 255評(píng)論 0 0
  • 一日一畫(huà),當(dāng)堅(jiān)持成為一種習(xí)慣,你會(huì)收獲什么呢?
    樹(shù)葉o英語(yǔ)規(guī)劃師閱讀 545評(píng)論 0 0

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