LoginSignup
178

More than 5 years have passed since last update.

UIScrollView を無限ループさせる

Last updated at Posted at 2012-07-10

UIScrollView にはループ機能は無いのでスクロールのタイミングでサブビューを再配置+スクロールのオフセットを戻して擬似的にループを再現させる方法がよく取られます。

例えば、

  • UIScrollView の中に5つの subview があり、

My cool picture

  • 右にスワイプしたとします。

My cool picture

  • スクロールが止まったらすぐに一番右のサブビューを抜き出して、一番左になるよう全ての subview を再配置。(A)

My cool picture

  • それと同時にスクロールオフセットを元の位置に戻す。(B)

My cool picture

  • 1サイクル完成。

My cool picture

これを繰り返せば無限ループしているように見えます。
(A) と (B) の処理を一瞬で行うため、subview の数によっては描画が追いつかないので、pagingEnabled = YES にして、かつ UIScrollView のデリゲートメソッド scrollViewDidEndDecelerating: の中で (A)+(B) の処理をすればスムーズに見えます。

拙作の InfiniteScrollView を使うと簡単。

■ GitHub InfinitePagingView
https://github.com/caesarcat/InfinitePagingView

  • 使い方

#import "InfinitePagingView.h"
 :
 :
/* インスタンス作成 */
InfinitePagingView *pagingView = [[InfinitePagingView alloc] initWithFrame:frame];
[self.view addSubview:pagingView];

/* サブビュー作成 */
UIImageView *page1 = [[UIImageView alloc] initWithImage:image1];
/* ページとして追加 */
[pagingView addPageView:page1];
    :
    :
/* 最低5個は必要 */

Screenshot0

  • AppStore のスクリーンショット風に1ページあたりのサイズ指定も可能

/* インスタンス作成 */
InfinitePagingView *pagingView = [[InfinitePagingView alloc] initWithFrame:frame];
/* 1ページあたりのサイズを指定 */
pagingView.pageSize = CGSizeMake(120.f, 100.f);


Screenshot0

  • 縦スクロールも可能

/* インスタンス作成 */
InfinitePagingView *pagingView = [[InfinitePagingView alloc] initWithFrame:frame];
/* 1ページあたりのサイズを指定 */
pagingView.pageSize = CGSizeMake(120.f, 100.f);
/* スクロール方向を垂直に指定 */
pagingView.scrollDirection = InfinitePagingViewVerticalScrollDirection;

Screenshot0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
178