本例可以實(shí)現(xiàn)長(zhǎng)按item實(shí)現(xiàn)拖動(dòng),重新排版collectionview,使用場(chǎng)景可以在首頁(yè)入口列表欄或者其他頁(yè)面允許用戶手動(dòng)修改入口菜單順序的地方
ps:直接上代碼
import UIKit
class ViewController: UIViewController ,UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
var collectionView : UICollectionView!;
var longPressGesture = UILongPressGestureRecognizer();
var itemArr = NSMutableArray();
override func viewDidLoad() {
super.viewDidLoad()
for _ in 1...100 {
let size = CGSize(width: 100, height: 50);
itemArr.add(size);
}
let layout = UICollectionViewFlowLayout.init();
self.collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "item");
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handlLongPress(gesture:)) );
longPressGesture.minimumPressDuration = 1
self.collectionView.addGestureRecognizer(longPressGesture);
self.view.addSubview(self.collectionView);
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1;
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return itemArr.count;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "item", for: indexPath) as UICollectionViewCell;
cell.backgroundColor = UIColor.darkGray;
return cell;
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return self.itemArr[indexPath.item] as! CGSize;
}
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
self.itemArr.exchangeObject(at: sourceIndexPath.item, withObjectAt: destinationIndexPath.item);
}
func handlLongPress(gesture: UILongPressGestureRecognizer) {
switch gesture.state {
case UIGestureRecognizerState.began:
guard let selectedIndexPath = self.collectionView.indexPathForItem(at: gesture.location(in: self.collectionView)) else {
break;
}
print("長(zhǎng)按開(kāi)始");
collectionView.beginInteractiveMovementForItem(at: selectedIndexPath);
case UIGestureRecognizerState.changed:
collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view));
case UIGestureRecognizerState.ended:
collectionView.endInteractiveMovement()
default:
collectionView.cancelInteractiveMovement();
}
}
}
因?yàn)槭茄菔拘詃emo,所以collectionviewCell未封裝,layout也是使用的最簡(jiǎn)單的流水布局.
備注:后期有時(shí)間繼續(xù)更新item大小不一致的demo