UICollectionViewCell 移動攻略

最近產(chǎn)品出了一個需要移動UICollectionViewCell需求,其中有點小挫折,與大家分享一下。

UICollectionView移動前提條件:

iOS版本必須大于iOS 9.0

Apple官方文檔,關(guān)于UICollectionView移動方法如下:

    // 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()

進(jìn)入正文,給UICollectionView增加移動步驟如下

1. 給collectionView增加長按手勢
2. 在手勢識別中,設(shè)置各種移動事件
3. 在delegate設(shè)置對應(yīng)cell是否可以移動
4. 在delegate中交換數(shù)據(jù)
5. 設(shè)置不可參與移動的IndexPath

具體代碼如下:

import DKImagePickerController

class CommodityImageEditVC: UIViewController {
    // 選取圖片框架
    var assets = [DKAsset]()
    
    let commodityImageEditCellID = "CommodityImageEditCellID"
    
    // 欄加載
    lazy var gridView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: 162.0, height: 162.0)
        flowLayout.sectionInset = UIEdgeInsets(top: 20, left: 50, bottom: 20, right: 50)
        flowLayout.minimumLineSpacing = 32.0
        
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
        collectionView.backgroundColor = UIColor.white
        collectionView.register(CommodityImageEditCell.self, forCellWithReuseIdentifier: commodityImageEditCellID)
        collectionView.dataSource = self
        collectionView.delegate = self
        return collectionView;
    }()
    

    
    // MARK: - life cycle
    override func viewDidLoad() {
        super.viewDidLoad()

        setupView()
        
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        // 設(shè)置表格視圖大小
        gridView.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - setup view
    func setupView() {
        
        view.addSubview(gridView)
        
        setUpLongPressGesture()
    }
    
    /**
     給gridView增加長按事件
     */
    func setUpLongPressGesture() {
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPressMoving(longPress:)))
        gridView.addGestureRecognizer(longPress)
    }

}


// MARK: - 長按手勢識別
extension CommodityImageEditVC {
    
    @objc func longPressMoving(longPress: UILongPressGestureRecognizer) {
        // 獲取長按點
        let point = longPress.location(in: longPress.view)
        
        if #available(iOS 9, *) {
            switch longPress.state {
            case .began:
                // 根據(jù)長按點,獲取對應(yīng)cell的IndexPath
                guard let indexPath = gridView.indexPathForItem(at: point) else {
                    return
                }
                gridView.beginInteractiveMovementForItem(at: indexPath)
                
            case .changed:
                
                gridView.updateInteractiveMovementTargetPosition(point)
                
                
            case .ended:
                gridView.endInteractiveMovement()
            default:
                gridView.cancelInteractiveMovement()
            }
        }
    }
    
}

// MARK: - dataSource delegate
extension CommodityImageEditVC: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return assets.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: commodityImageEditCellID, for: indexPath) as? CommodityImageEditCell
        if indexPath.row == assets.count {
            cell?.cellType = .add
        } else {
            cell?.cellType = .image
            cell?.updateCell(asset: assets[indexPath.row])
        }
        return cell!
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // 判斷選中的是否為增加圖片選項
        guard let cell = collectionView.cellForItem(at: indexPath) as? CommodityImageEditCell else {
            return
        }
        guard cell.cellType == .add else {
            return
        }
        let pickerController = DKImagePickerController()
        pickerController.didSelectAssets = {(assets: [DKAsset]) in
            self.assets.append(contentsOf: assets)
            self.gridView.reloadData()
        }
        present(pickerController, animated: true, completion: nil)
    }
    
    // 設(shè)置最后一個不可參與移動
    func collectionView(_ collectionView: UICollectionView, targetIndexPathForMoveFromItemAt originalIndexPath: IndexPath, toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath {
        if proposedIndexPath.item == assets.count {
            return originalIndexPath
        }
        if originalIndexPath.item == assets.count {
            return originalIndexPath
        }
        return proposedIndexPath
    }
    
    // 設(shè)置是否可以移動
    func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
        if indexPath.row == assets.count {
            return false
        } else {
            return true
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        // 移動后交換數(shù)據(jù)
        let moveData = assets.remove(at: sourceIndexPath.row)
        assets.insert(moveData, at: destinationIndexPath.row)
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 因為要結(jié)局swift3.0中引用snapKit的問題,看到一篇介紹Xcode8,swift3變化的文章,覺得很詳細(xì)...
    uniapp閱讀 4,512評論 0 12
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,349評論 25 708
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,245評論 4 61
  • 爸爸氣哭了媽媽, 媽媽眼淚如雨下。 “要不是掛念女兒, 我才不回這個家”。 媽媽的淚水, 爸爸的粗話, 沖垮家的土...
    元氣少女a(chǎn)閱讀 282評論 8 11
  • 昨天我哭了好幾次,也開心笑了好幾回。一天之內(nèi)哭哭笑笑組成我生活的日常。三毛說:對疼痛敏感的人就是對生活敏感的人。我...
    燕紀(jì)事閱讀 368評論 0 2