21
21

More than 5 years have passed since last update.

UIScrollView: 現在のページ番号を計算

Last updated at Posted at 2012-12-26

スクロール位置によってページ番号を計算する処理。
スクロールビューの中央を境にページ番号を増減するので、実際の見た目とページ番号の乖離も無いと思う。(round()で四捨五入しているのはそのため。)

縦方向の場合はX, widthをY, heightと読み替えれば良い。

ページ番号

// 横方向にページングする UIScrollView のページ番号を計算
- (NSUInteger)currentPageIndex:(UIScrollView*)scrollView
{
    CGFloat w = CGRectGetWidth(scrollView.frame);       // ページ幅
    NSInteger maxPageIndex = ;                           // 最大ページ番号(count-1)
    CGFloat positionX = scrollView.contentOffset.x;     // 現在の表示座標x
    CGFloat paging = round(positionX / w);              // 四捨五入して現在のページ番号を計算
    // (positionX / w) < x.5 のときは前のページ
    // (positionX / w) >= x.5 のときは次のページ


    // 範囲外のページ番号を調整
    paging = (paging >= 0.0) ? paging : 0.0;
    paging = (paging <= maxPageIndex) ? paging : maxPageIndex;


    return (NSUInteger)paging;
}

// UIScrollViewDelegate - スクロールの度呼ばれる
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSUInteger currentPageIndex [self currentPageIndex:scrollView];
    self.pageControl.currentPage = currentPageIndex; // UIPageControl にそのまま使える
    NSLog(@"Page Index: %d", currentPageIndex);
}

Swift
let offset = scrollView.contentOffset
let pageWidth = ...
let paging = min(max(round(offset.x / pageWidth), 0.0), CGFloat(pageCount))
21
21
0

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
21
21