Swift でページングを実装する
UICollectionView を使って一覧画面を作成していて、画面を一番下までスクロールしたら次ページをロードして表示する、というようにページング処理をさせたいときには、 UICollectionReusableView と UIActivityIndicatorView を使うと良いそうです。
これらを使ってページング処理をさせるときには、 UICollectionReusableView でフッターとなる View を作成し、 UIActivityIndicatorView でローディングインジケータを作成することになります。
ページング処理の大まかな流れは以下の通りです。
- 画面を一番下までスクロールするとフッターが表示される。
- フッターが表示されたらインジケータを表示する。ぐるぐるさせる。
- 次ページを読み込む処理を実行する。
- 次ページを読み込む処理が完了したらぐるぐるやめる。インジータを隠す。
フッターが表示されたら という部分は、 collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) を使うことで実装できます。
具体的には以下のように記述します。
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionFooter {
let reusableView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "UICollectionReusableView に設定した Idenfier", forIndexPath: indexPath)
// インジケータをぐるぐるさせる処理
// 次ページを読み込む処理
return reusableView
}
return UICollectionReusableView()
}