しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

UICollectionViewの並び替え

UICollectionViewでの並び替えを試してみました。

f:id:llcc:20171020143248p:plain

Storyboardを使わないでUICollectionViewを表示

まずは普通にUICollectionViewを表示してみます。
コードは下の通りです。

class CollectionViewController: UICollectionViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
        collectionView?.backgroundColor = UIColor.white
    }
    
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
        cell.backgroundColor = UIColor.lightGray
        
        return cell
    }
}

CollectionViewのレイアウトは下の通りです。

let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 100, height: 100)
layout.minimumLineSpacing = 10
layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)

実行すると下のようにCollectionViewが表示されます。

f:id:llcc:20171020134036p:plain

UICollectionViewの並び替え

UICollectionViewの並び替えはmoveItemAtを実装するだけで完了です。

class CollectionViewController: UICollectionViewController {
    override func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        
    }
}

これで下のように並び替えをする事ができるようになります。

f:id:llcc:20171020143349p:plain