スクロールビューを作成するときは、次のように設定してください。
scrollView.showsHorizontalScrollIndicator = false;
scrollView.showsVerticalScrollIndicator = false;
scrollView.pagingEnabled = true;
次に、サブビューを、インデックス*スクローラーの高さに等しいオフセットでスクローラーに追加します。これは垂直スクローラー用です。
UIView * sub = [UIView new];
sub.frame = CGRectMake(0, index * h, w, subViewHeight);
[scrollView addSubview:sub];
これを実行すると、ビューの間隔が空けられ、ページングが有効になっていると、一度に1つずつスクロールします。
したがって、これをviewDidScrollメソッドに入れます。
//set vars
int index = scrollView.contentOffset.y / h; //current index
float y = scrollView.contentOffset.y; //actual offset
float p = (y / h)-index; //percentage of page scroll complete (0.0-1.0)
int subViewHeight = h-240; //height of the view
int spacing = 30; //preferred spacing between views (if any)
NSArray * array = scrollView.subviews;
//cycle through array
for (UIView * sub in array){
//subview index in array
int subIndex = (int)[array indexOfObject:sub];
//moves the subs up to the top (on top of each other)
float transform = (-h * subIndex);
//moves them back down with spacing
transform += (subViewHeight + spacing) * subIndex;
//adjusts the offset during scroll
transform += (h - subViewHeight - spacing) * p;
//adjusts the offset for the index
transform += index * (h - subViewHeight - spacing);
//apply transform
sub.transform = CGAffineTransformMakeTranslation(0, transform);
}
サブビューのフレームはまだ間隔が空いており、ユーザーがスクロールするときに変換を介してサブビューを一緒に移動します。
また、上記の変数pにアクセスできます。これは、サブビュー内のアルファや変換など、他の目的に使用できます。p == 1の場合、そのページは完全に表示されているか、1に近づく傾向があります。