Collectionview实现拖动item重新排版-Swift
2016-12-08 本文已影响128人
强强刘
本例可以实现长按item实现拖动,重新排版collectionview,使用场景可以在首页入口列表栏或者其他页面允许用户手动修改入口菜单顺序的地方
Untitled.gifps:直接上代码
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("长按开始");
collectionView.beginInteractiveMovementForItem(at: selectedIndexPath);
case UIGestureRecognizerState.changed:
collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view));
case UIGestureRecognizerState.ended:
collectionView.endInteractiveMovement()
default:
collectionView.cancelInteractiveMovement();
}
}
}
因为是演示性demo,所以collectionviewCell未封装,layout也是使用的最简单的流水布局.
备注:后期有时间继续更新item大小不一致的demo